我已经覆盖了 Linux 平台中malloc
、calloc
和free
函数的函数,如下所示:
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
typedef void* (*MALLOCFN)(size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void (*FREEFN)(void *);
MALLOCFN real_malloc = (MALLOCFN) 0;
CALLOCFN real_calloc = (CALLOCFN) 0;
FREEFN real_free = (FREEFN) 0;
void *get_realfn(const char *fnm)
{
void *pfunc = (void *) NULL;
printf("searching for original %sn", fnm);
pfunc = dlsym(RTLD_NEXT, fnm);
if (pfunc) printf("found original %sn", fnm);
else printf("not found original %sn", fnm);
return pfunc;
}
void *malloc(size_t s)
{
printf("called mallocn");
if(real_malloc == NULL) real_malloc = (MALLOCFN) get_realfn("malloc");
if (real_malloc) return real_malloc(s);
else return NULL;
}
void *calloc(size_t s1, size_t s2)
{
printf("called callocn");
if(real_calloc == NULL) real_calloc = (CALLOCFN) get_realfn("calloc");
if (real_calloc) return real_calloc(s1, s2);
else return NULL;
}
void free (void * ptr)
{
printf("called freen");
if(real_free == NULL) real_free = (FREEFN) get_realfn("free");
if (real_free) real_free(ptr);
}
int main()
{
char * c1 = (char *) malloc(400);
char * c2 = (char *) malloc(400);
free(c2); free(c1);
return 0;
}
C 程序 (testalloc.c( 是使用 g++ 4.9.2 版本的编译器构建的:
g++ -g testalloc.c -ldl -o testalloc;
显示的前几行输出如下所示,它进入无限递归并崩溃:
called malloc
searching for original malloc
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
. . . .
请建议如何避免递归。
printf
函数可以分配内存。因此,当您在未分配"真实"函数指针之前调用printf
时,它会进入插入的函数中,从而导致无限递归。因此,不要在插入函数中使用printf
语句。
如果您确实需要打印某些内容,请使用 syscall(2)
,这将绕过 stdio 库函数。
#include <sys/syscall.h>
...
syscall(SYS_write, STDOUT_FILENO, "searching for originaln",
sizeof "searching for originaln" - 1);