[英]C++ program crashes after calling destructor containing delete operator
該程序執行直至析構函數的調用,但隨后因錯誤而崩潰:
HEAP CORRUPTION DETECTED ... CRT檢測到應用程序在堆緩沖區結束后寫入了內存。
盡管許多類似的線程都要求使用向量,但我還不知道如何使用向量。 我也認為我應該使用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];
}
Yu應該將矩陣分配放入構造函數中:
Matrix(int a = 0, int b = 0)
{
n_row = a;
n_col = b;
m = new int[n_col*n_row];
}
正如您所說,第二件事-您應該使用delete[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.