Jun 2, 2015

C/C++ Memory Leak and Valgrind

Memory leak is a problem that every C/C++ programmer, soon or later, will need to deal. They can exhaust the system memory and then undesired things will happen, like the process be just killed by the operating system, or worst, crash another running application that needs allocate memory, resulting an overall system failure.

A memory leak happens when you allocate some memory and then lose the control over it. This can be done allocating some memory region and then losing the pointer to its address, then that memory region can't be released nor used again, because nobody know its address. The code below do exactly this:

#include <cstdlib> 
#include <stdio.h>

int main(void)
 int *p;

  p = new int;

 return 0;

The pointer 'p' creates a new 'int' and then another, losing the address of the previous, repeating the process infinitely, until the system memory runs out and the OS/Linux kill and/or an overall failure happens. 

The video below show us in the first attempt to run, the OS/Linux kill the process, and in the second attempt the worst scenario seems to happen, the OS/Linux kill the process and X session, which runs out of memory too, look:

But this example was simple, what to do if I need fix a memory leak in a larger project? that's where some tools can help us, like the Valgrind ! let's try to find the memory leak using Valgrind, the syntax is simple:

valgrind --leak-check=yes ./a.out

The output:

==4048== Memcheck, a memory error detector
==4048== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4048== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4048== Command: ./a.out

**4048** new/new[] failed and should throw an exception, but Valgrind
**4048**    cannot throw exceptions and so is aborting instead.  Sorry.
==4048==    at 0x4029F27: ??? (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4048==    by 0x402A751: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4048==    by 0x80484E1: main (in /root/a.out)

As we can see, the tool identified the operator new int in the main function, being very useful for large and/or unknown projects that you may have to fix memory leaks. This is just a simple hello world, for more advanced examples you can take a look on Valgrind website.

About the Versions
  • Linux Ubuntu 12.04
  • Valgrind-3.10.0.SVN

0 comentários :

Post a Comment