0

this might be a simple question so accept my appolegises , I am creating a 2 dimetional pointers to int and I want to release the memory at the end but I think I'm doing It all wrong and all of the memory isn't being relaesed.

int **a;
a = new int *[bin->height];
for (int i=0;i<bin->height;i++)
a[i] = new int [bin->width];
for (int i=0;i<bin->height;i++)
            delete [] a[i];
            delete a;

am I doing it right ?

Edited by kshahnazari

3
Contributors
2
Replies
12
Views
3 Years
Discussion Span
Last Post by rubberman
0

Very close, and conceptually you've got it perfect. The only problem is a mismatch of new[] and delete when releasing a. This is what you want:

int **a;

a = new int *[bin->height];

for (int i=0;i<bin->height;i++)
    a[i] = new int [bin->width];

for (int i=0;i<bin->height;i++)
            delete [] a[i];

delete [] a;

When using new, you should have a corresponding delete. When using new[], you should have a corresponding delete[].

0

This is when having a class to handle this cruft is called for. That way, you can deal with the new/delete cruft in the constructors/distructor and when you are done with the instance, just delete the class instance. IE,

void 2darrayfunct(size_t height, size_t width)
{
    2darray array = 2darray(height, width);
    // Do stuff with array here.
    .
    .
    .
    // Now, done with array.
}

Leaving the function, the array is automatically destroyed as it has gone out of scope. Simple, complete, no leaks (assuming the 2darray class destructor is properly implemented).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.