0

I have written a program that fills a 3-d array with multyplication tables of an arbitrary size (I know it is not the most efficient code, but I have to stick to pointers). It compiles but when debugging around delete part it throws out this:

Unhandled exception at 0x0f8f59da (msvcr100d.dll) in 14chap-2.exe: 0xC0000005: Access violation reading location 0xfeeefee2.

I have searched through the web on the problem:

But could not find an appropriate answer. As I understand, the problem might lie in the wrongful use of new operator but for me it looks ok.

Here is the meaningful part of the code:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

int main () {
    int size;
    int size1;
    int size2;
    cin >> size;
    cin >> size1;
    cin >> size2;
    size += 2;
    size1 +=2;
    size2 +=2;
    int ***pp = new int ** [size];

    for (int i = 0; i < size; i++) {
        pp [i] = new int* [size1];

        for (int j = 0; j < size1; j++) {
            pp [i][j] = new int [size2];
        }
    }

    cout << '\n';

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size1; j++) {
            if (i == 0 || j == 0) {
                pp[i][0][0] = i-1; 
                pp[0][j][0] = j-1;
                cout << pp[i][j][0];
            } else {
                pp [i][j][0] = pp[0][j][0]*pp[i][0][0]; 
                cout << pp[i][j][0];
            }
        }
        cout << '\n';
    }

    for (int i = 0; i < size; i++) {
        delete [] pp[i];    
        for (int j = 0; j < size1; j++) {
            delete [] pp [i][j];
        }
    }

    delete [] pp;

    cin.get();
    cin.ignore();
}   
APerson
  • 8,140
  • 8
  • 35
  • 49
VVG
  • 141
  • 1
  • 13

1 Answers1

4

You must first delete [] the pp[i][j] arrays, and only then pp[i]. And pp last.

Now you're first deleting pp[i] and then trying to access pp[i] to delete pp[i][j], which will cause undefined behavior because pp[i] is already deleted at that point.

Rule of thumb: Call delete [] in the exact opposite order than you did new [].

Emil Laine
  • 41,598
  • 9
  • 101
  • 157