谁能告诉我为什么在 ubuntu 的 G++ 上运行时调用我的 delete2DMatrix 函数会导致段错误?
我在 CLion 中运行它并且它执行完美并且没有抛出段错误,所以我非常困惑为什么它会抛出 G++ 的段错误。我已经确认这是导致段错误的删除功能。如果我删除该功能,一切都会完美执行。
我的职能是:
void delete2DMatrix(int ***matrix, int rows){
for(int i=0; i < rows; i++){
delete [] matrix[i];
}
delete [] matrix;
}
这是我创建矩阵的函数,所以你可以看到我确实调用了 new
:
int **create2DMatrix(int rows, int columns){
int **matrixPtr;
matrixPtr = new int *[rows];
for(int i = 0; i < rows; i++){
matrixPtr[i] = new int [columns];
}
//Sets all values to the default 0
for(int i =0; i< rows; i++){
for (int a = 0; a < columns; a++){
addMatrixValue(matrixPtr, i, a, 0);
}
}
return matrixPtr;
}
我已经确认传递的指针实际上指向矩阵。我也能够毫无问题地向矩阵添加值。仅当我调用此删除函数且仅在 G++ 中时,它才会抛出段错误并检测到内存泄漏。
提前致谢。
最佳答案
根据为矩阵分配内存的方式判断,
void delete2DMatrix(int ***matrix, int rows){
...
}
是不对的。使用:
// ||
// vv Don't need the additional pointer.
void delete2DMatrix(int **matrix, int rows){
...
}
在评论中,您说:
I cannot change the ***matrix in the delete because my professor created the declarations and we are not allowed to change them. He uses his own .h file when grading, so I have to use ***matrix.
在这种情况下,您需要使用:
void delete2DMatrix(int ***matrix, int rows){
int** ptr = *matrix;
for(int i=0; i < rows; i++){
delete [] ptr[i];
}
delete [] ptr;
// I am guessing that your professor wants to have *matrix
// set to nullptr in this function.
*matrix = nullptr
}
看来你的教授的编码习惯仍然是 C 类的。如果他们想将 matrix
的值设置为 nullptr
,他们可以使用更多的 C++ 习惯用法并传递对变量的引用。
void delete2DMatrix(int**& matrix, int rows){
for(int i=0; i < rows; i++){
delete [] matrix[i];
}
delete [] matrix;
matrix = nullptr
}
关于c++ - 删除 [] 导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372234/