Greg wrote:
John Harrison wrote:
John Harrison wrote:
Gr*****@nosp am.com wrote:
Hey,
this is related to absolutely nothing in particular and is of no
importanc e whatsoever except for my curiousity.
Does anybody have an example of a particularly tricky memory leak
that's hard to spot. I'd like to see something that's a little unusual
or obscure. something that involves some in depth knowledge about
functionali ty X or scenario X and that causes a memory leak. Something
that would be really easy to miss.
This is simply for curiousity sake and nothing more. if anybody has a
little code snippit or example I'd love to see it
cheers
G
How about this
class Dodgy
{
Dodgy() : ptr(new char[99]) {}
~Dodgy() { delete[] ptr; }
char* ptr;
X x;
};
If the X constructor throws an exception then the memory allocated will
never get freed, even through the destructor does free the memory. This
is because in this case the destructor for Dodgy is never called.
john
But this version is OK
class NotDodgy
{
NotDodgy() : ptr(new char[99]) {}
~NotDodgy() { delete[] ptr; }
X x;
char* ptr;
};
No memory leaks there.
I would note that this example is for illustrative purposes only, no
actual program would rely on something as fragile as the order of
member declarations. Such a requirement is too easy to overlook and too
fragile to maintain.
Absolutely, but Graham was looking for 'a particularly tricky memory
leak that's hard to spot', 'something that's a little unusual
or obscure' and 'Something that would be really easy to miss'.
Making pointer code exception safe is tricky. Another reason not to use
pointers of course. If I had to use pointers for some reason then I
would allocate memory in the body of the constructor.
class Safe
{
Safe() : ptr(0) { ptr = new char[99]; }
~Safe() { delete[] ptr; }
X x;
char* ptr;
};
This code will not leak memory irrespective of initialisation order issues.
john