Checking usage of realloc with Valgrind

Full article: Checking usage of realloc with Valgrind

Summary: realloc has a surprising number of tricky corner cases to watch out for. Valgrind Memcheck will help you find various issues like using it with bad arguments, pointers that might have become invalid, and leaks of blocks that have been resized.

Also, don’t forget to use GCC with -fanalyzer, -Wuse-after-free, and -Wfree-nonheap-object to catch some of these issues early.

Finally, there is the almost philosophical question of what it means to have a zero-sized memory block. Since different implementations of (and standards describing) realloc answer that question differently, it is best to avoid ever calling realloc with size zero.

If you do then Valgrind 3.21.0 has two options to help:

  • --show-realloc-size-zero=no|yes. Warn for size zero realloc calls.
  • --realloc-zero-bytes-frees=yes|no. Whether size zero returns NULL or not.

Both options were implemented by Paul Floyd.