trouble deleting at array of arrays

closed account (S8hvC542)
I have an array of arrays. When needed I allocate as shown as follows. With this allocation method, I am able to access the values using normal array notation:

histogram[i][i] = blah blah;

1
2
3
4
5
6
7
8
9
10
11
if (histogram == 0) {
  histogram = new int*[bytesPerPixel];

  for (i = 0; i < bytesPerPixel; i++) {
    histogram[i] = new int[256];

    for (j = 0; j < 256; j++) {
      histogram[i][j] = 0;
    }
  }
} 


However, whenever I try to use the following code to delete the allocated memory, the execution simply returns "Aborted". Any ideas? It's got to be something simple, but I'm just not seeing it.

1
2
3
4
5
6
if (histogram != 0) {
  for (i = 0; i < bytesPerPixel; i++) {
    delete[] histogram[i];
  }
  delete[] histogram;
}

just write delete []histogram;

1
2
3
4
if (histogram != 0) {
  for (i = 0; i < bytesPerPixel; i++) {
    delete[] histogram[i];
  }


is not needed.
Last edited on
closed account (S8hvC542)
Okay, that did not work, but I discovered something else. My destructor method (which is doing the memory deletion) is being called four times even though I only call it 3 times as I only had 3 objects.

My quick research tells me though that I should not be calling the destructor myself? Does C++ just take care of this for me since I explained how to delete my objects? I'm just surprised by this as I did not have this issue on another program I coded which called the destructor for each object I instantiated.
Oh,yes!!
Thank you for pointing out my mistake.
Try this.
Add histogram = NULL; after delete []histogram.
Last edited on
closed account (S8hvC542)
Hmmm, I did NULL my other dynamic arrays, but forgot to for this particular one as you pointed out.

So the execution just bombs out because it finds a memory leak or something?

Thanks for the help.
The for loop that deletes each of the elements in histogram is needed.

I can't find anything in the code that could cause the problems you're seeing. AFAICT, this code is correct.
closed account (S8hvC542)

Thanks guys for the help.

I went back to

1
2
3
4
5
6
if (histogram != 0) {
  for (i = 0; i < bytesPerPixel; i++) {
    delete[] histogram[i];
  }
  delete[] histogram;
}


and it works now fine even with the second "delete" which is not in the for loop. It seems my only mistake was not including

histogram = NULL;
Topic archived. No new replies allowed.