Barry Tormey
Barry Tormey

Reputation: 3126

Heap Corruption Detected in C++

I keep getting the error Heap Corruption Detected. I have read through several questions on here, but I can't quite find out what is causing this in my code. I am trying to create a 2d array that will hold a matrix that is read from a text file.

// Create a 2d matrix to hold the matrix (i = rows, j = columns)
matrix = new int*[cols];

for(int i = 0; i <= cols; i++) {
    matrix[i] = new int[rows];
}

// Populate the matrix from the text file
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        inputFile >> matrix[i][j];
    }
}

My destructor is:

for(int i = 0; i <= cols; i++) {
    delete[] matrix[i];
}

delete[] matrix;

I've tried debugging, but that does do much help in this case. Any suggestions?

Upvotes: 0

Views: 273

Answers (2)

user645280
user645280

Reputation:

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        inputFile >> matrix[i][j];

When you allocated you went from 0 to cols in i. Now you're changing i to be rows.

EDIT: Below would honor your commented row/column rules and follow RAII:

std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

for( int i=0; i<rows; ++i ) {
   for( int j=0; j<cols; ++j ) {
      inputFile >> matrix[i][j];
   }
}

// no need for delete matrix cleaned up when leaving scope.

Upvotes: 0

Summer_More_More_Tea
Summer_More_More_Tea

Reputation: 13356

matrix = new int*[cols];

for(int i = 0; i <= cols; i++) {
    matrix[i] = new int[rows];
}

For an array with cols elements, the index is from 0 to cols - 1 inclusively.

The heap corruption will be detected when

delete [] matrix;

Since matrix[cols] write a position out of array bound.


UPDATE

As @DanielKO (thank you buddy :p) pointed out in the comment

there is a mismatch, the "Populate the matrix..." loop makes "i" iterate over "rows" when it should be iterating over "cols".

Upvotes: 5

Related Questions