[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Array<T>::nil_rep leaks memory
From: |
Jaroslav Hajek |
Subject: |
Re: Array<T>::nil_rep leaks memory |
Date: |
Tue, 23 Sep 2008 19:19:36 +0200 |
On Tue, Sep 23, 2008 at 3:11 PM, John W. Eaton <address@hidden> wrote:
> On 23-Sep-2008, Jaroslav Hajek wrote:
>
> | Well, as much as I understand it, the static object will be correctly
> | deallocated at the end of the program, while the new-allocated object
> | (on heap, presumably) is *never* freed. It's not much of an issue, but
> | it is a memory leak.
>
> If that were true, then repeatedly running a program like
>
> int main (void) { char *x = new char [134217728]; return 0; }
>
> would quickly make your system unusable. But it does not, as the
> resources allocated to the program are freed when the program exits.
>
True, but that is an OS feature. Modern OSes (Linux, at least) simply
track memory allocated by a process and deallocate it on exit. But the
program itself does not do it. In particular, non-trivial destructors
are not called. The following program demonstrates the problem:
#include <iostream>
class A
{
int x;
public:
A (int xx) : x(xx) { std::cout << "constructing A " << x << '\n'; }
~A () { std::cout << "destructing A " << x << '\n'; }
};
A* a0 ()
{
static A a(0);
return &a;
}
A* a1 ()
{
static A * a = new A (1);
return a;
}
int main ()
{
A * aa0 = a0 (); // this doesn't leak
A * aa1 = a1 (); // this leaks
}
On my system, this outputs:
constructing A 0
constructing A 1
destructing A 0
--
RNDr. Jaroslav Hajek
computing expert
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz