MALLOC_PERTURB_ helps find real bugs

I admit I had no idea about the existence of MALLOC_PERTURB_ until a recent post on fedora-devel list by Jim Meyering.

The feature is simple yet effective. It makes glibc return malloc(3)-ated memory initialized to the value of the environment variable MALLOC_PERTURB_ and clear free(3)-d memory to the bitwise inverse of MALLOC_PERTURB_‘s value. This way you can easily spot places in your code which use memory before it is initialized or reuses freed memory.

I decided to give it a try and run the test suite of SSSD. Guess what – I got an instant crash. It turned out that we reused already freed memory in our program, but since we reused it almost instantly, the contents were still there and we never saw the bug during our testing.

I highly recommend using MALLOC_PERTURB_ during development of your software as it can help find bugs that would otherwise manifest themselves only sometimes making it very hard to debug (and ultimately fix!) them.

For more information, refer to the thread on fedora-devel or read some more on Ulrich Drepper’s journal.