Dave's Brain

Browse - Programming Tips - My program has a memory leak but I am deallocating everything I allocate.

Date: 2010feb7
OS: Windows
Language: C/C++

Q.  My program has a memory leak but I am deallocating everything I allocate.
How can I fix it?

A.  It could be that your memory is getting fragmented.
Use pools / private heaps.  For example if your program reads a file,
parses it into chunks that are new'ed then delete's all of them.  And
does this many times.  You can put all those new's into a pool and free
up the entire pool when done with the file.

On Windows use:

HANDLE hHeap; // Make the heap that will be used for one file hHeap = HeapCreate(0, 10 * 1024, 0); // Initially 10K, no upper limit LPVOID pChunk1 = HeapAlloc(hHeap, 0, size_of_first_chunk); LPVOID pChunk2 = HeapAlloc(hHeap, 0, sizof_second_chunk); ... // When done HeapDestroy(hHeap);
There is also Boost.pool On Linux, you can use the Apache Portable Runtime pools: http://apr.apache.org/docs/apr/0.9/group__apr__pools.html

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.