Hi there, I am writing quite a large program in
C++ that runs continuously and unfortunatley has
some huge memory leaks. (Every iteration it
loses roughly 8-16kB) I've checked everything I
can think of and still have no idea where they
are coming from. Every new has a corresponding
delete. All vectors or large structures are
local and therefore give back their memory when
their methods return. I am using PostgreSQL and
every PQexec has a corresponding PQclear and I
only do PQconnectdb's once at the beginning. I
really can't think of anything else. Here's some
more background info: The program takes roughly
52MB of memory initially. My computer has
roughly 773MB. Every memory loss seems to be in
4kB segments. I am running on a SuSe Linux
The really weird thing about this is that I was
tracing the program in debug mode while watching
the free memory via the 'free' command. The
memory would drop at one point in the code,
however, the next iteration through it would
drop at another point of the code different than
the first point. It also seems to be dropping
everywhere in my code; I can't seem to pinpoint
the place. So any ideas? I've certainly run out
Thank-you so much for your time in advance!
Hello Joe, thanks for the question.
From what you've said, I came across a couple of things that could be the cause. As you state that your vector and structures are local and give back their memory. If the vector has had any object pushed onto it which had it's memory dynamically allocated, and you don't delete that memory and clear the vector, then that memory will be leaked. Maybe sizeof of the structure objects pushed onto the vector is 4kb.
One thing you can do to help track down your problem is to incorporate a memory monitor into your project. What you do is make a global header file with the new and delete operators overloaded to call free and malloc. Also, you write out to a text file the amount of bytes allocated and freed, so you can better track a leak down. Here's an example.
void* operator new (unsigned int uNumBytes)
sprintf(buffer, "Allocated %d bytes", uNumBytes);
fwrite(buffer, sizeof(char), strlen(buffer), pFile);
That way after you open a text file, every time you allocate some amount of memory with new, you have it logged in the text file. Same principle with delete. This is how I personally track down leaks and I find that it generally helps. If not, if you want to paste some code up there I'll be happy to take a look at it.
I hope this information was helpful.