Search code examples
c++heap-corruption

Heap corruption detected error in C++


Here is my code:

#include<iostream>
#include<cstdlib>

using namespace std;

int main() {
    int** arr=NULL;
    int num=0;
    cin >> num;
    int* big=NULL;
    arr = new int*[num];
    for (int i = 0; i < num; i++) {
        arr[i] = new int[5];
    }
    big = new int[num];

    for (int i = 0; i < num; i++) {
        for (int j = 0; j < 5; j++) {
            while (1) {
                cin >> arr[i][j];
                if (arr[i][j] >= 0 && arr[i][j] < 100)
                    break;
            }
        }
    }

    for (int i = 0; i < 5; i++) {
        big[i] = 0;
    }

    for (int i = 0; i < num; i++) {
        for (int j = 0; j < 5; j++) {
            if (big[i] < arr[i][j]) {
                big[i] = arr[i][j];
            }
        }
    }

    for (int i = 0; i < num; i++) {
        cout << "Case #" << i + 1 << ": " << big[i] << endl;
    }

    delete[]big;
    for (int i = num-1; i>=0; i--) {
        delete[]arr[i];
    }
    delete[]arr;

    return 0;
}

When I run this code, it says that there are heap corruption error (heap corruption detected). I think it means that there are some errors at 'new' or 'delete' parts in my codes, but I cannot find them. I hope someone to answer. Thanks.


Solution

  • Error is here:

    big = new int[num];
    ...
    for (int i = 0; i < 5; i++) {
        big[i] = 0;
    }
    

    So when you have num less than 5 you are writing outside the array.

    Anyway you are using C++ so use vector for such tasks.

    #include<iostream>
    #include<cstdlib>
    #include<vector>
    
    using namespace std;
    
    int main() {
        vector<vector<int>> arr;
        int num=0;
        cin >> num;
        arr.resize(num, vector<int>(5));
    
        for (auto &row : arr) {
            for (auto &cell : row) {
                while (1) {
                    cin >> cell ;
                    if (cell >= 0 && cell < 100)
                        break;
                }
            }
        }
    
        vector<int> big(arr.size());
        for (int i = 0; i < arr.size(); i++) {
            for (auto &cell : arr[i]) {
                if (big[i] < cell) {
                    big[i] = cell;
                }
            }
        }
    
        for (int i = 0; i < num; i++) {
            cout << "Case #" << i + 1 << ": " << big[i] << endl;
        }
    
        return 0;
    }