0

The following code compiles but runs with mistake:

int main() {
    int (*d)[2] = new int[3][2];
    // do something
    delete [] *d; // this is wrong
    delete [] *(d+1); // this is also wrong
    //delete [] d; // this works
    return 0;
}

I do not know why "delete [] *d" does not work because *d seems to be a pointer to a chunk containing 2 integers and delete[] should destroy that chunk.

Furthermore, I am not sure whether "delete [] d" is enough to release all six elements since two-dimension array is involved here.

Thanks!

2
  • 1
    delete what you new, and only what you new. The new-expression here returned d, not *d and not *(d+1). Commented Oct 10, 2016 at 19:47
  • int (*d)[2] says "*d is an array of two ints". An array is not a pointer. Commented Oct 10, 2016 at 20:09

2 Answers 2

4

The memory you allocated is allocated as one continuous block (or chunk) of memory that stores an array obejct of int[3][2] type. It should be freed as one block

delete [] d;

That's all you need to do.

Freeing just some partial sub-block of a whole block is not supported by C++ dynamic memory management mechanisms.

Your delete [] *d is indeed wrong - the behavior is undefined. However, it has a good chance of "working" in practice since int (*)[2] pointer d and [decayed] int * pointer *d point to the same spot in memory, and the underlying types are trivial. If it "works", it should typically have the same effect as delete [] d;, i.e. free the entire 2D array.

Sign up to request clarification or add additional context in comments.

Comments

0

int[3][2] is not a pointer of pointers but just a multi-dimensional array, allocated as a single pointer.

You cannot delete "lines" of it because there are no lines. Memory is contiguous.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.