Advertisement

Deleting dyn. alloc'ed arrays safely?

Started by November 15, 2000 11:37 AM
2 comments, last by HBringer 24 years, 2 months ago
Okay, my recent posts to the board here turn out to mostly be caused by something like the following scenario:


int ** foo;

this->foo = new int * [2];
this->foo[1] = new int [4];

.
.
.

for (int x = 0; x < 2; x++)
{
     delete [] foo[x];
}

delete [] foo;

   
The catch is, in this sequence, foo[0] doesn't point to anything; while foo[1] points to an array (or, has a valid second dimension - if you look at it that way). When I delete the "second dimension" from foo, I need to be able to check to see if it has been allocated; otherwise I get a nasty debug error. "if (foo[x] != NULL)" doesn't appear to work, so can someone suggest a logic test that DOES check for an allocated "second dimension" or array for each element in the "first dimension" of foo? Thanks! --HB Edited by - HBringer on 11/15/00 11:40:08 AM
Whenever you dynamically allocate memory, you must assume that the data it contains is garbage. Always assume new memory is uninitialized. This is not true of all operating systems (NT, for example, gives you 0-filled memory), but you must assume this to be portable.

So to solve your problem, when you allocate the first dimension of your array (that which will hold each 2nd dimension array), you need to initialize that data to 0:
  int ** foo;foo = new int* [2]; // note, this-> is redundantmemset (foo, 0, 2 * sizeof (int*));foo[1] = new int[4];// ...// ...for (int x = 0; x < 2; x++){  delete [] foo [x];}delete [] foo;  

The magic is the memset line. It initializes the memory of the array to 0, so you can check against NULL later (if you choose). 2 * sizeof (int*) is the size of the first dimension of the array (in bytes).

Note I don''t check for NULL here. It is legal to delete something that is NULL--the delete operation just returns immediately. However, it''s slightly more efficient to check against NULL before deleting; you save the function call overhead to the delete operator. If you''re not doing this in a tight loop, it''s nothing to worry about.
Advertisement
BTW, you don''t need to check for foo != NULL.

You can simply go

if(!foo)
...

Thanks,
Etnu

Sometimes I think I know what I really don''t, but then again usually I do know what I don''t, but just don''t realize it, maybe its because I am so young, but then again it could be because I am insane.

---------------------------Hello, and Welcome to some arbitrary temporal location in the space-time continuum.

Most compilers will optimize (foo != NULL) to !foo...

This topic is closed to new replies.

Advertisement