How can I check for actual memory leaks at runtime with Valgrind?

In some programs, part of the allocated memory is not destroyed at all, but they are required for the entire execution time of the program. Hence, it is generally considered safe.

But there are other objects that are not intended for the entire execution time of the program, but are not destroyed due to developer mistakes. These are actual memory leaks that need to be addressed.

When we run the following Valgrind command, it only displays general leaks after the program finishes executing. Hence, can someone elaborate on how to distinguish the above two scenarios from the result of Valgrind's leak check.

The command I used to find memory leaks;

valgrind --log-file=valgrind_output.txt --tool=memcheck --leak-check=yes ./MyTestProgram

      

Typical output at the end of execution;

==10108== LEAK SUMMARY:
==10108==    definitely lost: 392,323 bytes in 1,164 blocks
==10108==    indirectly lost: 178,120 bytes in 4,283 blocks
==10108==      possibly lost: 170,155,118 bytes in 3,347,087 blocks
==10108==    still reachable: 263,778,326 bytes in 3,935,669 blocks

      

Is there a function in Valgrind like Tap in the IBM Purify tool that can detect an ongoing memory leak at runtime?

+3


source to share


3 answers


You can use 2 different methods to find the leak at runtime.



+3


source


Is there a function in Valgrind like Tap in the IBM Purify tool that can detect an ongoing memory leak at runtime?



No no. Valgrind cannot know if there is a leak if the program is not finished, because it cannot know what will be released when the program ends.

+2


source


You can force your program to deliberately crash during a run to make sure you can check the allocated memory at that point. You can do this by adding a signal handler for a specific custom signal such as SIGUSR1.

signal(SIGUSR1, myhandler); 

      

in your handler, you do something like this:

printf("debug exit!\n"); 
int *ptr = 0; 
*ptr = 0xdeadbeef; 

      

Then you can send this signal to your application like this:

kill -s SIGUSR1 `ps -aux| grep myapp | head -n -1 | awk '{print $2}'`

      

Then you can check the differences in the number of selected objects. If you know the numbers should stay the same, or if some number keeps growing, you can check where this is happening and see if there is a memory leak.

0


source







All Articles