我想 "覆盖" malloc
在纯C语言和Linux GCC中,用于内存检查的东西。注意 malloc()
是一个弱符号,在纯C语言中可以这样做,即把一个强符号的 malloc()
.
但我刚刚发现它崩溃,如果调用 printf()
在我 malloc()
实现,如果删除,就不会崩溃。
要重现。
#include <stdio.h>
extern void *__libc_malloc(size_t size);
static int cnt = 0;
void* malloc(size_t size) {
printf("--- calling customized malloc\n");
cnt += 1;
if(cnt > 1) return NULL;
return __libc_malloc(size);
}
static void leak_test1() {
int* a = malloc(sizeof(int)*5);
a[0] = 3;
}
int main(){
leak_test1();
printf("cnt=%d\n", cnt);
return 0;
}
是否意味着 "在我自己的malloc()中调用printf无效"?深层原因是什么?(如果我说的不对,请纠正我)
有可能 printf
召唤 malloc
的缓冲区,以分配给 stdout
所以你会得到一个无限的递归。
你也许可以通过调用 fprintf(stderr, ...)
作为 stderr
是无缓冲的。