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?
source to share
You can use 2 different methods to find the leak at runtime.
-
On the vgdb run command line leak_check There are other optional arguments for leak control commands, for example. to find available memory, or just memory that has increased or ... See valgrind user manual: http://www.valgrind.org/docs/manual/mc-manual.html#mc-manual.monitor-commands
-
Inside your program: You can add leak detection programs to your client requests. For example. insert "calls" into VALGRIND_DO_LEAK_CHECK or VALGRIND_DO_ADDED_LEAK_CHECK See http://www.valgrind.org/docs/manual/mc-manual.html#mc-manual.clientreqs for more details
source to share
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.
source to share