One of the most scary problems when I develop an application is a buffer overflow, that happens when you access a memory zone that it doesn’t have be assigned. The problem is that if you overwrite that zone, not always the program crashes, but it stills continues running with that zone corrupted. And, if you are lucky, the program crashes after 10 lines, 50 or God knows.
One of the most used applications to find buffer overflows is Valgrind. It is very sophisticated, and is able to find other type of problems. The drawback is that it only runs on x86, AMD, PPC32 and PPC64.
When I was studying, I discovered Electric Fence, a library that detect illegal accesses to memory. Roughly speaking, it changes the malloc function, so when a buffer is allocated, it adds around it a “red zone”: if you touch that zone, the program aborts with a segmentation fault. What is the advantage? It always crashes in the moment you access an invalid position of memory, not 100 or 300 lines far away. So you can use a debugger and see in which line is crashing: surely, in that line there is an illegal access to memory.
How to use it? More simply, impossible. You only need to link your program with
the library (-lefence
). That’s all! A banner is showed when the program is
executed. Even you may use the Electric Fence with an already compiled program
if you preload first the library (exporting the LD_PRELOAD environment
variable to libefence.so.0.0
).
The drawback with Electric Fence is that it makes the program more more slow. So use it only when developing, and disable it in the final release.
And remember: Electric Fence is in almost all GNU/Linux distributions. Happy bug hunting!