所以我想在析構函數中刪除2D sq_matrix。然而,它給了我一個內存錯誤:如何在.h文件中破壞這個二維數組?
*** glibc detected *** ./hw1.out: free(): invalid pointer: 0x0000000000d6ccb0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x31dd675f3e]
/lib64/libc.so.6[0x31dd678d8d]
./hw1.out[0x4011af]
./hw1.out[0x400f54]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x31dd61ed1d]
./hw1.out[0x400a69]
======= Memory map: ========
00400000-00402000 r-xp 00000000 fd:02 99359246
/* some memory map here */
Aborted (core dumped)
這裏的.h文件,我把我的代碼:
#ifndef SQUAREMATRIX_H
#define SQUAREMATRIX_H
#include <iostream>
using namespace std;
template<class T>
class SquareMatrix{
public:
int size;
T** sq_matrix;
SquareMatrix(int s){
size = s;
sq_matrix = new T*[size];
for(int h = 0; h < size; h++){
sq_matrix[h] = new T[size];
}
}
~SquareMatrix(){
for(int h = 0; h < size; h++){
delete[] sq_matrix[h];
}
delete[] sq_matrix;
}
void MakeEmpty(){
//PRE: n < width of sq matrix
//POST: first n columns and rows of sq_matrix is zero
}
void StoreValue(int i, int j, double val){
//PRE: i < width; j < height
//POST: sq_matrix[i][j] has a non-null value
}
void Add(SquareMatrix s){
//PRE: this.SquareMatrix and s are of the same width and height
//POST: this.SquareMatrix + s
}
void Subtract(SquareMatrix s){
//PRE: this.SquareMatrix and s are of the same width and height
//POST: this.SquareMatrix - s
}
void Copy(SquareMatrix s){
//PRE: s is an empty matrix
//POST: s is a ixi matrix identical to this.SquareMatrix
}
};
所以我主要做的就是創建一個二維數組構造之外,並分配內存中的構造函數。然後,我嘗試刪除析構函數中的指針,但它仍然給我一個錯誤。這裏是我的主要方法:
#include <iostream>
#include "SquareMatrix.h"
using namespace std;
int main(){
int size;
int val;
cout << "Enter the width and height of the square matrix: ";
cin >> size;
SquareMatrix<int> sq1(size);
SquareMatrix<int> sq2(size);
return 0;
}
謝謝!
爲什麼當這顯然是C++的C標籤? – GhostCat
我沒有在這裏得到這個錯誤:http://codepad.org/VjuVRA9v。是否有更多的代碼沒有提供? –
你不遵守[3]規則(http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree)。您按值傳遞'SquareMatrix'對象,要做到這一點,您需要正確實施必要的複製操作。 – PaulMcKenzie