Deleting a 2D or 3D pointer created with new

Viewed 56

How do I delete a 2D or 3D pointer created with new? I know a 1D pointer can be deleted by delete [] name_of_pointer.

// 1D pointer:
int *pt1 = new int[size];             // Creating 1D pointer
delete [] pt1;                        // Deleting 1D pointer


// 3D pointer   L: # of layers, R: # of rows, C: # of columns
int (*pt2)[L][R][C] = new int[1][L][R][C];   // L:2, R:2, C:3 (ex. below)
delete [] pt2;

I used this to create and delete a 3D pointer but it only removed the first two entries of pointer pt2, remaining 10 entries remained intact no matter how many times I ran the code.

Eg:

int B[2][2][3] = {{{0,1,2},{3,4,5}},{{6,7,8},{9,10,11}}};

int (*pb)[2][2][3] = new int[1][2][2][3];

for(int k=0; k<2; k++){
    for(int j=0; j<2; j++){
        for(int i=0; i<3; i++){
            *(*(*(*(pb)+k)+j)+i) = B[k][j][i];
            cout << "k,j,i: " << k << "," << j << "," << i;
            cout << " " << B[k][j][i] << " " << *(*(*(*(pb)+k)+j)+i) << endl;
        };
        cout << endl;
    };
    cout << endl;
};

delete [] pb;


for(int k=0; k<2; k++){
    for(int j=0; j<2; j++){
        for(int i=0; i<3; i++){
            cout << "k,j,i: " << k << "," << j << "," << i;
            cout << " " << B[k][j][i] << " " << *(*(*(*(pb)+k)+j)+i) << endl;
        };
        cout << endl;
    };
    cout << endl;
};

I got garbage values for (k,j,i) = (0,0,0) & (0,0,1) after performing delete operation on pb, rest all 10 values remain unchanged.

1 Answers

Your code is checking a deleted array's values. This is undefined behavior. There is no way to safely check the values that those elements now have as they no longer exist.

In addition delete[] is not required to "zero out" the objects it deletes. You can't assume that because the memory isn't modified the objects aren't deleted.

Related