BSDnexus
16Dec/10Off

Tuning malloc

According to the (Linux) malloc man page calling free twice on the same memory location is a certain crash:

Crashes in malloc(), calloc(), realloc(), or free() are almost always related to heap corruption, such as overflowing an allocated chunk or freeing the same pointer twice.

...something along the lines of:

$ ./a.out
*** glibc detected *** ./a.out: double free or corruption (top): 0x0944c008 ***

however, according to the same man page, this is now a tunable feature

Recent  versions  of  Linux  libc  (later  than 5.4.23) and glibc (2.x) include a malloc() implementation  which  is  tunable  via  environment variables.   When  MALLOC_CHECK_  is  set,  a  special (less efficient) implementation is used which is designed to be tolerant against  simple errors, such as double calls of free() ... If MALLOC_CHECK_ is set to  0,  any  detected  heap  corruption  is  silently ignored ...

I decided to create a simple test to see this in action. Exactly as detailed, I ran the compiled code with the environment variable and the program exited successfully.

$ MALLOC_CHECK_=0 ./a.out
$ echo $?
0

Sample code follows

#include <stdlib.h>
 
int
main(void) {
 char * foo;
 
 foo = (char *) malloc(500);
 
 free(foo);
 free(foo);
 return(0);
}