Error when trying to delete 2D dynamic array [closed]

  c++

I’ve been trying to construct and delete dynamic 2D arrays, but so far whenever the row and column isn’t equal and I delete the array, Microsoft Visual C++ runtime library shows me this error: HEAP CORRUPTION DETECTED: after Normal block (#190) at 0x00CED508
CRT detected that the application wrote to memory after end of heap buffer
Here’s the code:

#include <iostream>
using namespace std;

void initialize(int**& a, int& m, int& n)
{
    a = new int*[m];
    for (int i = 0; i < n; i++)
    {
        a[i] = new int[n];
    }
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << "Enter a[" << i << "][" << j << "]: ";
            cin >> a[i][j];
        }
    }
}

void del(int**& a, int& m)
{
    for (int i = 0; i < m; i++)
    {
        delete[] a[i];
    }
    delete[] a;
}

void print(int**& a, int& m, int& n)
{
    for (int i = 0; i < m; i++)
    {

        for (int j = 0; j < n; j++)
        {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
}

int main()
{
    int m, n;
    int** a;
    cout << "Enter the number of row and column: ";
    cin >> m >> n;
    initialize(a, m, n);
    print(a, m, n);
    del(a, m);
}

Am I doing something wrong here?

Source: Windows Questions C++

LEAVE A COMMENT