Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valgrind - Find memory leak in a shared library

I need to know ways to find out the memory leaks in a shared library which will be loaded to a release binary. I mean shared library I built with -g option but the binary that loads the shared library is not built with -g option.

I get the leak report as follows.

==739==    at 0x4A05809: malloc (vg_replace_malloc.c:149)
==739==    by 0x84781B1: ???
==739==    by 0x87507F5: ???
==739==    by 0x874CF47: ???
==739==    by 0x874E657: ???
==739==    by 0x874F7C2: ???
==739==    by 0x8779C0C: ???

Please let me know how to get the stack trace of the leak from the shared library?

like image 839
Naga Avatar asked Sep 27 '12 12:09

Naga


2 Answers

Assuming that the leak really is coming from your shared library then I don't think the problem is the lack of debugging in the main executable.

More likely your problem is that the executable is unloading the shared library by calling dlclose before it finishes. That means that when valgrind comes to check for leaks all the symbol information for the library is gone as the library is no longer loaded.

If you can rebuild the executable then the easiest solution may be to temporarily stop it calling dlclose so that the library stays loaded until the end.

If you can't do that, then try using LD_PRELOAD to keep the library loaded, like this:

LD_PRELOAD="/path/to/library.so" valgrind my-executable

which will hopefully trick the dynamic linker into keeping the library loaded even after it has been closed.

like image 136
TomH Avatar answered Sep 22 '22 02:09

TomH


As the previous answer suggests, this is because you have closed your libraries before the program terminates and therefore symbol information is not available to valgrind.

Using LD_PRELOAD didn't work for me; I now have two builds; one that explicitly does not call dlclose(); on this build, valgrind correctly reports line number information as you would expect with dynamic linking.

like image 29
Doug Avatar answered Sep 19 '22 02:09

Doug