C++ 程序在调用包含删除运算符的析构函数后崩溃

C++ program crashes after calling destructor containing delete operator

此程序执行到调用析构函数但随后崩溃并出现错误:

HEAP CORRUPTION DETECTED...CRT detected that the application wrote to memory after end of heap buffer.

虽然很多类似的帖子要求使用vector,但我还不知道如何使用vector。另外我认为我应该使用 delete[ ] 而不是 delete。但奇怪的是,当我使用 delete[ ] 时,程序比我不使用 delete[ 时早一步崩溃(即在显示矩阵之前) ]

如何摆脱这个错误?这是否与 for 循环的使用有某种联系?

代码如下:

#include<iostream>

using namespace std;

class Matrix
{
  int n_row, n_col;

  public:

  Matrix(int a = 0, int b = 0)
  {
     n_row = a;
     n_col = b;
  }

  int *m = new int[n_col*n_row];

  ~Matrix()
  {
     cout << "\t deallocating memory\t\n\n";
     delete m;                //ERROR??
  }
 void input_M(int a[], int r, int c);

 void display_M(int a[], int r, int c);

};

void Matrix::input_M(int a[], int r, int c)
{
  cout << "\nEnter elements row-wise\n";
  for (int i = 0; i < r; i++)
      for (int j = 0; j < c; j++)
          cin >> a[i*j + j];
}

void Matrix::display_M(int a[], int r, int c)
{

   for (int i = 0; i < r; i++)
   {
       cout << "\n\n\n";
       for (int j = 0; j < c; j++)
         cout << a[i*j + j] << "\t";
   }
 }


int main()
{
   cout << "  C++ Program to display MATRIX ";

   int r1, r2, c1, c2;

   cout << "\n\n Enter the number of Rows for the First Matrix\t\t:\t";
   cin >> r1;

   cout << "\n\n Enter the number of Columns for the First Matrix\t:\t";
   cin >> c1;

   cout << "\n\n Enter the number of Rows for the Second Matrix\t\t:\t";
   cin >> r2;

   cout << "\n\n Enter the number of Columns for the Second Matrix\t:\t";
   cin >> c2;

   Matrix s1(r1, c1), s2(r2, c2);

   cout << "\nEnter elements for the first Matrix\n";

   s1.input_M(s1.m, r1, c1);       //ALIAS??

   cout << "\nEnter elements for the second Matrix\n";

   s2.input_M(s2.m, r2, c2);
   system("cls");

   cout << "\t\tMatrix 1\n\n";
   s1.display_M(s1.m, r1, c1);

   cout << "\n\n\n\n\t\tMatrix 2\n\n";
   s2.display_M(s2.m, r2, c2);

   system("pause");
   return 0;
 }

要删除一个数组,你必须使用方括号delete[] m;

例如:

int *m = new int[n_col*n_row];
delete[] m;

int *m = new int; // single element
delete m;

至于你的其他问题,你的程序崩溃的原因是

    Matrix(int a = 0, int b = 0)
    { 
        n_row = a;
        n_col = b;
     }

     // this line is executed before you set n_row and n_col
     int *m = new int[n_col*n_row]; 

解决方法:确保 n_row 和 m_col 已设置,然后再使用它们创建动态数组

Matrix(int a = 0, int b = 0) : n_row(a), n_col(b), m(new int[a*b]) {    }
or
Matrix(int a = 0, int b = 0)
{
    n_row = a;
    n_col = b;
    m = new int[a*b];
}

你应该把你的矩阵分配放到构造函数中:

  Matrix(int a = 0, int b = 0)
  {
     n_row = a;
     n_col = b;
     m = new int[n_col*n_row];
  }

第二件事,正如你所说 - 你应该使用 delete[]