Qt Destructors and Garbage collection
-
I'm using a mathematical-intensive library for my program. The person who wrote that library had alot of mathematical knowledge, but no knowledge of C++ and destructors. The library is written in plain C++ (without any Qt), and there is extremely many memory leaks.
When I run one instruction in that library, about 50mb of memory is lost.Is it in some way possible to do some kind of garbage collection in my Qt program to remove these leaks? I know Qt doesn't support automatic garbage collection, but I'm hoping someone has a creative idea to fix this.
Going through the library and fixing these leaks myself is also no option, since the library is about 60000 lines of code.
-
Well,
Franzk is right, there's no general solution from the application point of view, the problem is in the code itself.
Anyway, if you're using Linux, you can use Valgrind or use these two methods to build up all the data you need to lookup leakage by yourself:
"Hooks for Malloc":http://www.gnu.org/s/libc/manual/html_node/Hooks-for-Malloc.html
"Backtrace":http://www.gnu.org/s/libc/manual/html_node/Backtraces.htmlNote that this is not the full solution for you. It's just a hint. You can set up the hooks in the main(), and then store in a global QMap< void*, QStringList > all backtraces related to the allocated memory that has not been deallocated. Finally you can save the QMap content in a file, and debug all leakages (at least the biggest number of them) one by one (maybe some of them has the same leakage reason, so you should solve a group of them, run again, and so on).
Tony.
-
You can use a tool like "valgrind":http://valgrind.org/ or similar to track the memory leaks. It shows you where the memory was allocated that is not released in the end.
As a rule of thumb: the code section or class that allocates memory is responsible to release it after use (as long as "ownership" of the memory is not transferred intentionally).
-
i've done a valgrind check and it says 7864 leaks. And I'm not going to fix those.
So I'm probably going to use some other library.thanks anyway
-
I know this post is from a while ago now, but wanted to chime in. Even though the other answers are correct, they aren't the whole story.
All memory gets allocated from some heap associated with a process. So, if you cant fix the code itself, your other options are to alter the heap used by that code, or the process where that code lives.
Heap control, so far as I know, is pretty platform specific. But, QProcess would allow you to, fairly generically, start up a new process and communicate with it.
In effect, you could arrange your leaking library as a separate "server" process that you "reboot", dumping all the memory it has leaked, at whatever interval seems appropriate.
Not an ideal solution, but it's a potential option.