How to track/fix a memory-related issue in a large C/C++ code on *nix systems
Solution 1
If you can change the source code, Dmalloc is great; it will list which pointers were unfreed and (for code built with debugging symbols) exactly which line they were allocated on.
If you can't, Valgrind is pretty much the standard for that sort of thing. I generally find Valgrind somewhat harder to use, but it has way more features and doesn't involve adding dmalloc calls into your code
Solution 2
valgrind is amazingly helpful.
Solution 3
Massif (from valgrind) is one of the best way to find memory leaks. Repeat your suspicious code (or run your program long enough) and dump the result with ms_print. Usually, the call stack is giving you enough information to fix it.
With GDB, you can try to attach to a running program and call functions such as malloc_stats()
If your program is written in a different language, it might be more tricky. Recently, some GDB has gained scriptability, and people started interesting projects such as gdb-heap, which can analyze Python memory from a core dump. Similar memory analysys scripts might be possible for C++ objects.
Read also https://stackoverflow.com/questions/2564752/examining-c-c-heap-memory-statistics-in-gdb
Solution 4
For Solaris, there's several tools listed in the answers to this StackOverflow question (they include leak checking with other forms of bad memory access).
Solution 5
I have been doing Objective-C for some time, and there is an analyzer that deal with C level memory management and stuff like that. Clang Static Analyzer is so good that Apple decided to bundle it with their xCode IDE. I'm not sure if this is good for your question, but if you are doing C then it's worth a try.
Related videos on Youtube
Hemant
Updated on September 17, 2022Comments
-
Hemant over 1 year
What strategy you use while tracking a memory-related issue? What tools do you use (open source as well as proprietary) to identify memory leaks, memory corruption etc? How would you track memory leaks if only gdb/dbx available on a system?
For me, fixing memory leaks with only a debugger is very hard.
-
Admin over 13 yearsPersonally I think this question is more programming related than unix related.
-
-
Daniel James over 13 yearsMinor quibble: clang was developed for use in xcode from the start. See clang.llvm.org/clang_video-05-25-2007.html
-
phunehehe over 13 yearsHi Daniel, that might be true, but it wasn't included in xCode until recently (or at least not in the bundle I downloaded from Apple)
-
Admin over 13 yearsdmalloc is not very performant as expected in very large systems. valgrind is a better bet, and even there you will hit bottlenecks...
-
rajaganesh87 about 13 yearsvalgrind --tool memcheck "yourapp" will give memory related info in runtime (useful in desktop systems). Another great tool is memwatch but it should be compiled along with your source. Memwatch can log details to a file hence more suitable for embedded systems.