Re: delete for 2D arrays

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



On 13 Apr 2006 13:41:34 -0700, "SLC" <dotnetchic@xxxxxxxxx> wrote:

if I have a 2D array of data as in:

int **foo = new int *[first_dimension];
for (i=0; i<first_dimension; i++)
{
foo[i] = new int [second_dimension];
}

will a single call to delete free my memory?

delete [] foo;

No. The compiler has no way of knowing what each foo[i] points to, much
less how (and if) it should be deleted.

or do I need to delete each dimension?

for (i=0; i<first_dimension; i++)
{
delete [] foo[i];
}
delete [] foo;

The second one is what you need. BTW, foo is not a 2D array but a sort of
simulation consisting of an array of pointers to arrays. If
second_dimension is known at compile-time, you could use a real (dynamic)
2D array:

int (*foo)[second_dimension] = new int[first_dimension][second_dimension];

Now this one you would delete with:

delete [] foo;

The difference is that my example creates a 2D array whose data is
contiguous. Your individual row arrays might be spread all over memory.
There is an advanced trick whereby you can get contiguous data even when
the first and second dimensions aren't known until runtime. It involves
allocating a single chunk of memory to contain the row pointers, which
point to the rows within that same chunk of memory, so everything resides
in the same block. You have to take some pains to get the alignment right
for the rows, which follow the row pointer array.

--
Doug Harrison
Visual C++ MVP
.



Relevant Pages

  • Re: classes and __init__ question
    ... have a dog class. ... parameters) behind the scenes to create the class Foo itself, ... thinking of, for example, a game board array where each member of the ... ends up using too much memory *and* memory profiling shows the board ...
    (comp.lang.python)
  • Re: large number of variables
    ... In the 3D array approach, ... can be stored in a register or stored in memory. ... the compiler move computations out of the loop. ... the timings aren't well enough known to tune ...
    (comp.lang.fortran)
  • Re: Why in stdint.h have both least and fast integer types?
    ... Space savings might translate into ... Wouldn't it be OK to let the compiler represent int_fast16_t as ... BECAUSE IT TAKES LESS MEMORY? ... >> of a big array used in another compilation unit. ...
    (comp.lang.c)
  • Re: gdb not catching out-of-bounds pointer
    ... that, for example, accesses one array from a pointer to another is ... provided the library writer knows what the compiler writer guarantees ... The portability of an allocator depends on the source of raw memory. ...
    (comp.unix.programmer)
  • Re: wrappers that accept either a vector or matrix
    ... necessarily contiguous in memory (they can be rather arbitrary ... whether an array is contiguous, ... You can help the compiler using the CONTIGUOUS attribute, ... or explicit-shape declaration. ...
    (comp.lang.fortran)