2

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?

Community
  • 1
  • 1
TimeString
  • 1,778
  • 14
  • 25

2 Answers2

5

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • I'm more interested in what's going on after I do `new int[100][100]`: Does it allocate a continuous memory segment or does it allocate 100 segments, each segment contains 100 elements? – TimeString Feb 01 '17 at 23:18
  • @TimeString Please post a new question – Brian Bi Feb 01 '17 at 23:20
  • It seems `int (*ptr)[100][100] = new int[100][100][100];` first creates an array of pointer of int[100][100], but the later two dimensions int[100][100] seem to be a contiguous segment. – TimeString Feb 01 '17 at 23:38
  • @TimeString No, it does not. It has to be just 100 `int[100][100]` arrays. – HolyBlackCat Feb 02 '17 at 00:28
1

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 []

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79