Reputation: 19487
I know this is hardly a new question, but I haven't found anything elsewhere that works. I've got a C program that steadily eats memory as it runs - I use the 'free' command to track it, and I can see the amount of available memory is decreasing as long as it executes, which shouldn't be happening. However, I can't find anything in the program itself that could be causing this. I've also tested it with valgrind and dmalloc, and nether of them are able to detect any memory loss.
How do I find the leak?
Upvotes: 1
Views: 1484
Reputation: 50017
Is the memory actually leaked, or does the program simply consume more memory the longer it runs? In other words, is the program perhaps building a large dynamic data structure (linked list, etc) that simply continues to grow? As long as the program has a pointer to the memory it's not really a leak - but if the allocations are never freed each new one will get more memory from the OS. That would also explain why the tools you used reported no "leaks".
When I've had to do this I've done things like write a log message to a flat file every time my program allocated memory and freed it. The messages would include things like filename and program line where the memory was allocated and the address returned from malloc when allocating memory, or likewise the filename and program line where the memory was being freed and the address of the buffer being freed. Then you can sort the resulting file by address, and those addresses with an "ALLOCATE" message but no "FREE" message are the ones that may have leaked - or at least weren't freed by the time the program terminated. This can be time-consuming to implement and automated tools are nicer if you've got them - but depending on your circumstances you may have to do something like this.
Or, you might want to just punt and use a garbage collector. The Boehm collector might work for you - take a look at http://www.hpl.hp.com/personal/Hans_Boehm/gc/.
Share and enjoy.
Upvotes: 3
Reputation: 2678
If you're sure about your usage of memory, perhaps it's not your mallocs and frees that are the problem.
If you're using any libs, you should double-check that you use them correctly. Many have initialisation and freeing functions that you can easily forget, and thus cause memory leak(s).
Upvotes: 3