Home > fun > From the “When I was your age” department

From the “When I was your age” department

January 18th, 2009

Back in my day, we used to have to walk to school.  In the snow.  Uphill.  Both ways.  And we liked it!

Okay fine, I took a school bus just like you.  But, back in my day, we would sometimes see these dreaded words when coding/debugging in C or C++:

Segmentation fault (core dumped)
#

At that point, the feeling of dread sets in.  Its obvious to you, and anyone shoulder surfing, that you were not careful with your memory allocation.  To boot, if your application was any more complicated than say, “Hello World”, you would be faced with the task of firing up GDB, loading the core file, and tracking down exactly where you went wrong.   While being able to do this is indespensible, I have always found prevention to be better than the cure.

While working on my new project, I wanted to know how I was doing with memory allocation.  Enter Valgrind:

st-george-dragon

Valgrind is useful to help you find memory leaks and identifiying when you are accessing memory that has not been allocated.  Additionally, it will find incorrect uses of the free/delete operators.  Valgrind does this by running your program in a simulated, managed environment complete with a simulated CPU.  Effectively, while your program is running under Valgrind, it is being treated as if it were Java byte code.

To use Valgrind, first modify your make file to use the -g and -O0 options. This will turn on debugging information (so you get line numbers) and insures that the compiler is not running any optimizations (which is the default mode).  Keep in mind that your program will run many orders of magnitude slower when running under Valgrind.

Once that is done, simply run your program like this:
valgrind --leak-check=yes myprog arg1 arg2

To find out more about interpreting the error messages you get back, look here.

fun

  1. No comments yet.
  1. April 19th, 2010 at 23:09 | #1
  2. April 21st, 2010 at 22:12 | #2