(C++) Delete isn't working on 2D array...

Associate
Joined
20 Nov 2005
Posts
52
Hi, I'm new to C++, I can't get my head around why this isn't working...

I'm creating a 2D pointer to an array of unsigned char's like so:

Code:
unsigned char **ImagePtr;
ImagePtr = new unsigned char *[width];
for (int i=0 i<width; i++)
{
     ImagePtr[i] = new unsigned char[height];
}

The 2D array is for storing a greyscale image...the image is being loaded into the array correctly and I can manipulate and write it back to file etc. But when I come to delete the array - the memory isn't being freed/deleted...

Code:
for (int i=0; i<width; i++)
{
   delete[] ImagePtr[i];
}
delete[] ImagePtr;

But after doing this, if I print say ImagePtr[x][y]; the values are still there, surely by trying this the program should crash?

Many thanks if anyone can see what I'm doing wrong...
 
This is normal. For speed, the c++ standard library will not overwrite the contents of blocks which have been allocated on the heap after being freed - in release mode anyway. In debug mode, they usually overwrite with a pattern which it can detect later, rather than 0, to catch heap corruption errors.
You can overload/replace delete if you really want to zero-out the heap after you're done with it.
An analogy is with filesystems, when you delete a file, the filesystem usually just removes the reference to that file from the FAT/MFT/btree, rather than overwriting that file with 0's before removing it.
 
Back
Top Bottom