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)