Benad's Web Site

One of my biggest issues with C development, especially when you have to write code that handles complex structures and lots of string manipulation, is how easy it is to accidentally mess up you memory. By messing up with memory, I don't mean just trying to use NULL pointer, that's relatively easy to avoid. Here are the common errors you can make.

The first easy error is what is commonly called "off-by-one". For example, you have an array of size n, and you write at an index x >= n, or at memory location p > base + n.

The second error is the well-known memory leak. You don't always have the luxury of adding a garbage collector like gc to your code.

The third error is reading unset memory, i.e. code that depends on a value that's read even before it is even set. I know, most platforms initialize memory allocated on the heap to the value 0 in all memory positions, but still this is really bad.

I found a free, open-source for Linux called Valgrind that can detect any of the above errors at run-time. It runs your compiled program (written in any language, not just C) in an environment where all memory accesses are monitored. Obviously, this adds a large overhead (expect you code to run up to 20x slower), but Valgrind is very thorough. It really helped me make my C code "just" perfect...

Published on February 2, 2006 at 15:40 EST

Older post: Javolution: Recycle Your Objects!

Newer post: Best.. Birthday... Gift... Ever... Thank you Dave!