Using Valgrind to Detect Memory Management Problems

The C language has a reputation for being difficult to learn and to code in. I think this is unfair as it is actually a very small and simple language, but most of the perceived difficulty with using C comes from its memory management, or rather lack of. Only the smallest and simplest programs can get away with using auto variables: sooner or later you are going to have to use dynamic memory, opening yourself up to an extensive range of tricky bugs. There's no foolproof way to get round this, but you can catch most bugs before they wreak havoc in production with a brilliant little program called Valgrind.

Continue reading

Allocating Dynamic Memory in Large Blocks

When creating a dynamic data structure it is tempting to allocate just the amount of extra memory you need to add each item. However, malloc, realloc or calloc are quite expensive in terms of resources so for situations where many items are likely to be added it is more efficient to allocate a large block of memory in one go. This can be gradually used up, and then another block allocated when necessary. In this post I will write a simple demonstration of this principle, complete with monitoring code to verify that we are in fact improving efficiency.

Continue reading