Re: memory leak in the code?
 
On Jan 5, 5:21 pm, "Andrew Koenig" <a...@acm.org> wrote:
"Erik Wikstr=F6m" <Erik-wikst...@telia.com> wrote in message
news:zPNfj.2462$R_4.1902@newsb.telia.net...
Yes, but what about if you get a bad_alloc when allocating a? Then you
will try to delete whatever memory that the garbage in a points to. To
prevent this use something like this instead:
try {
 int* a = 0;
 a = new int[N];
 int* b = new int[N];
}
catch (bad_alloc)
{
 delete[] a;
}
Well, the idea is right but the implementation is wrong,
because a will be out of scope in the delete statement.
Moreover, unless a and b are deleted inside the try, the code
will leak memory if it succeeds, because once a and b are out
of scope, there's no further opportunity to delete the memory.
An alternative:
    int* a = 0;
    try {
        a = new int[N];
        int* b = new int[N];
        // do additional work here
        delete[] b;
        delete[] a;
    } catch (bad_alloc) {
        delete[] a;
    }
I agree with you that smart pointers are the way to go here :-)
But not std::auto_ptr, since it does delete ptr, and not
delete[] ptr.
I actually disagree about using smart pointers here.
std::vector seems far more appropriate.
--
James Kanze (GABI Software)             email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34