You are here:

C++/memory leaks


Hi there, I am writing quite a large program in   
C++ that runs continuously and unfortunately 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   
of them.   
Thank-you so much for your time in advance!   

Hello Joe,
Thankyou for your question. Without seeing your
code it is really hard for me to find out the
source of leaks, but thats what i can suggest
to you right now

But it seems obvious that one of the following two cases must
1. That a 'new' doesn't have an associated 'delete' or
2. That the SQL binding is leaking.
If he uses C++ vectors, he has to make sure that he frees any pointer
associated to it (a simple 'clear' will not do it for him). For
the following code will create a 1MB leak:

std::vector< char * > vect ;
for ( int i = 0 ; i < 1024 ; ++i )
  vect.push_back( new int[ 1024 ] ) ;
vect.clear() ;

Freeing up every cell is necessary before the 'clear':

std::vector< char * >::iterator it;
for ( it = vect.begin() ; it != vect.end() ; ++it )
  delete [] *it ;

Apart from it, its very hard for me to find the code
leak without seeing your code. Please have a look at
it, i hope it will help you.

Please take care,


All Answers

Answers by Expert:

Ask Experts




I can answer any question about functions,pointers,structures,object oriented programming basics of classes and data structures.My strong field is structured programming.


I have got 2 years experiece under C . I am able to answer about the structured concepts pointers to a little extent,OOP concepts. I have also experience in data Strucutres like Linked List, Stacks , Queues, Heaps, B Trees, Red Black Trees. I will try to satisfy with my knowledge. I am the Student of an expert here Martin, what i have learnt today, i just owe my every knowledge to him. He is the greatest.

©2017 All rights reserved.