ChrisZZ
ChrisZZ

Reputation: 2181

Calling printf in own malloc function caused segmentation fault

I'd like to "override" malloc in pure C with Linux GCC, for memory checking stuffs. Notice that malloc() is a weak symbol, it's OK to do that in pure C. i.e. Making a strong symbol of malloc().

But I just found it crash if calling printf() inside my malloc() implementation, and if removing, it won't crash.

To reproduce:

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

Does it mean "calling printf is invalid in my own malloc()"? What's the deep reason? (Correct me if I'm wrong)

Upvotes: 3

Views: 636

Answers (1)

chqrlie
chqrlie

Reputation: 145079

It is possible that printf call malloc to allocate the buffer for stdout, so you get an infinite recursion.

You might be able to get around this issue by calling fprintf(stderr, ...) as stderr is unbuffered.

Upvotes: 2

Related Questions