调用包含删除操作符

时间:2016-02-14 18:52:42

标签: c++ destructor delete-operator

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

  

HEAP CORRUPTION DETECTED ... CRT检测到应用程序在堆缓冲区结束后写入内存。

虽然许多类似的线程要求使用向量,但我还不知道如何使用向量。另外我认为我应该使用删除[] 而不是删除。但奇怪的是,当我使用删除[] 时,程序比我没有使用删除[] 时更早一步(即在显示矩阵之前)崩溃。 。

如何摆脱此错误?这是否与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;
 }

2 个答案:

答案 0 :(得分:1)

要删除数组,您必须使用括号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];
}

答案 1 :(得分:1)

Yu应该将你的矩阵分配到构造函数中:

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

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