That is because your
delete
code does not match the allocation code:
int **myArray = new int*[x];
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
myArray[i] = new int[j];
}
}
for (int i = 0; i < x; ++i) {
delete [] myArray[i];
}
delete[] myArray;
For each
x
you are allocating
y
arrays which are all assigned to
myArray[i]
. So only the last allocated one will be used (and later freed). Also this last one has the size of
y-1
which is the reason for the heap corruption because you are accessing one more (not allocated) item.
Just use a single loop for allocation like when deleting:
for (int i = 0; i < x; ++i) {
myArray[i] = new int[y];
}