TimeString
TimeString

Reputation: 1798

Delete or delete[] over new int[][]

I know in general if you new an instance of an object or a primary data type, you use delete; if you allocate an array such as new int[10], you free the memory by delete[]. I just came across another source and find out that in C++11, you can new a multidimensional array like this:

auto arr = new int[10][10];

My question is: Should I use delete or should I use delete[]? I would say delete[] looks more correct for me, however, delete doesn't crash the following program:

#include <stdio.h>

int main() {
    for (int i = 0; i < 100000; i++) {
        cout << i << endl;
        auto ptr = new int[300][300][300];
        ptr[299][299][299] = i;
        delete ptr;  // both delete and delete[] work fine here
    }
    return 0;
}

Why is that?

Upvotes: 2

Views: 1540

Answers (2)

Alex Guteniev
Alex Guteniev

Reputation: 13644

You could new such array before C++11.

    int (*p)[300][300] = new int[300][300][300];

C++11 only gives 'auto' sugar.

This is not three-dimentionally dynamic array, it is dynamic only by first direction, i.e. dymamic array of two-dimentional statio arrays.

You can say

    auto p = new int[rand()][300][300];

But you can't say

    auto p = new int[300][rand()][300];

So since this is ordinary dynamic array, use ordinary delete []

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119164

Always delete[] when the object allocated is an array (including an array of arrays, i.e., a multidimensional array). Using delete when you are supposed to use delete[], or vice versa, is undefined behaviour. It may appear to work but there is no guarantee.

Upvotes: 5

Related Questions