在自己的 malloc 函数中调用 printf 导致分段错误

Calling printf in own malloc function caused segmentation fault

我想 "override" malloc 在带有 Linux GCC 的纯 C 中,用于内存检查。请注意 malloc() 是一个弱符号,在纯 C 中这样做是可以的。即制作 malloc().

的强符号

但我发现如果在我的 malloc() 实现中调用 printf() 它会崩溃,如果删除,它不会崩溃。

重现:

#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;
}

是否意味着"calling printf is invalid in my own malloc()"?深层原因是什么? (如果我错了请纠正我)

有可能printf调用mallocstdout分配缓冲区,所以你得到一个无限递归。

您可以通过调用 fprintf(stderr, ...) 来解决这个问题,因为 stderr 是无缓冲的。