Correct memory usage in C with Valgrind

posted in: C | 0

Here is a quick how to use Valgrind tool to check if you have invalid usage of memory in C.

Configuration

Install valgrind:

compile your program with debug informations using gcc -g flag

Launch your program with valgrind:

 Normal usage

If we write a normal C program that allocate memory and free it normally the valgrind output will be like this:

main.c:

output:

 Memory leaks:

Memory leaks are bad in two way:

  • They can slow down your program.
  • They can crash your program in case it does not have enough memory.

How valgrind notify us of memory leaks? Let’s find writting a leaking program:

The valgrind output will be:

In the LEAK SUMMARY section, we can read that we didn’t free 10 bytes that correspond to our test variable that was allocated but not free’d.

Invalid access to memory

Sometimes in C, it’s possible to access memory that was not defined by you, valgrind list those access in the invalid read section. For example the following program tries to access a part of memory which is out of bound of our allocated char *:

In this case the program runs good on most environment but could face undefined state while using the read value. valgrind list those access as invalid read:

We can see that in main.c line 7 we attempted to read a part of memory which was not allocated by our program. The size of the read is useful in debugging as you can also guess the type of the data from the size.

 

Invalid writing of memory

The same behavior is available for writing memory out of allocated space:

Which output invalid write:

 Conclusion

  • Valgrind is really useful while building complex projects where memory leaks could happen.
  • I found that sometimes, while using external libraries that the output could be flooded by those leaking libs.
  • Even if the program runs good with inavalid read/write, this should NEVER happen in your code!
  • valgrind can be invoked with lot of different options that can fine tune its output or activity!

Have fun!

Leave a Reply