简体   繁体   中英

Valgrind: Where is my memory leak?

I am working on a rather chaotic library (client/server application) which has a memory leak somewhere, but I cannot find where.

When I start the library and let it do its work, I get the following memory usage using top when it finished:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND            
21010 root      20   0  111m  12m 6836 S  0.0  0.7   0:29.20 myapp
21008 root      20   0  172m  99m 6480 S  0.0  5.8   0:14.39 myapp

The first line is the client, the second the server. I let valgrind execute the server and got the following result:

==20904== 
==20904== HEAP SUMMARY:
==20904==     in use at exit: 4,723,124 bytes in 199 blocks
==20904==   total heap usage: 40,423,345 allocs, 40,423,146 frees, 1,977,998,844 bytes allocated
==20904== 
==20904== LEAK SUMMARY:
==20904==    definitely lost: 0 bytes in 0 blocks
==20904==    indirectly lost: 0 bytes in 0 blocks
==20904==      possibly lost: 914 bytes in 18 blocks
==20904==    still reachable: 4,722,210 bytes in 181 blocks
==20904==         suppressed: 0 bytes in 0 blocks
==20904== Rerun with --leak-check=full to see details of leaked memory
==20904== 
==20904== For counts of detected and suppressed errors, rerun with: -v
==20904== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2) Killed

If I understand this correctly, valgrind says that the server has just about 4,7M of memory still allocated with no real leaks. It can be that there are no "real" leaks, but normally the library should at this state have freed all resources. I cannot see any part in the code where something is not freed.

How can I find out where the resources are still allocated?

You could use a brute-force method and print to a log file before each allocation and after each delete.

You may want to print the object's size (or the size allocated) and maybe the name of the object.

You are looking for matching pairs, allocation and deallocation.

You may also want to print out the invocation number which will help match, ie if there are 4 invocations of allocation, you should be able to find deallocation #3 to match with allocation #3.

This requires careful inspection of the code to verify that all allocations have been identified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM