UNIX malloc() debugging

If you suspect memory leaks or corruption in your program due to the improper use of pointers, here are several things you can use, ordered by simplicity:

  • GNU libc’s malloc check. Set the MALLOC_CHECK_ environment variable to 1 to spam stderr when corruption is detected, or 2 to call abort() when corruption is detected.
  • Dmalloc. A debug malloc library that works as a drop-in replacement for the system malloc(), realloc(), and free() functions.
  • Electric Fence. This is a replacement malloc library similar to Dmalloc. Its manner of operation is to use the hardware memory protection of the processor to cause an immediate segmentation fault if the process attempts to write to memory preceding or following an allocated region.
  • Valgrind‘s memcheck tool. Valgrind runs the program under an emulated CPU, so the execution is quite a bit slower. However, it catches all memory corruption and pointer errors at runtime and prints a backtrace. It also prints memory leak and other statistics at the program exit. Invoke with valgrind –tool=memcheck <program>.

Here is another list I ran across.

Leave a Reply