释放对象的校验和不正确
incorrect checksum for freed object
我收到此错误(内存位置因运行而异):
q2(4910,0x7fff7a1d4300) malloc: *** error for object 0x7fdf79c04bd8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
这是崩溃的函数:
public:
// construct a 'rows X cols' matrix.
SMatrix(int rows, int cols) {
if (rows<1 || cols<1) {
cout<<"Invalid row/col value(s).";
exit(-1);
}
this->_rows = rows;
this->_cols = cols;
this->_vertical = new simpleNode [rows];
this->_horizontal = new simpleNode [cols];
if (this->_vertical == NULL || this->_horizontal==NULL) {
cout<<"Exiting";
exit(-1);
}
initArrays();
}
它在此特定行上崩溃:
this->_horizontal = new simpleNode [cols];
调用以下内容的函数:
int main() {
SMatrix bigM(500,500);
bigM.setElement(10,20,17);
cout <<" bigM - total size in bytes: (implementation depended): "
<< bigM.sizeInBytes() << endl << endl;
SMatrix m1(7,10),m2(7,10),m4(10,2),m5(7,2); //Crashes on m4(10,2)
}
其他可能相关的功能:
struct simpleNode {
Node* _next;
};
int _rows; //Number of rows in this SMatrix
int _cols; //Number of columns in this SMatrix
simpleNode * _vertical; //array (simpleNode)
simpleNode * _horizontal; //array (simpleNode)
/*Initiate the horizontal/vertical arrays to point to null*/
void initArrays() {
int i;
for (i=0; i<this->_rows; i++)
this->_horizontal[i]._next = NULL;
for (i=0; i<this->_cols; i++)
this->_vertical[i]._next = NULL;
}
我在OSX上。我用 -g 编译并使用 GDB 运行它,但程序正常退出。如果我不使用 XCode,如何调试它?关于如何解决问题的提示也将非常有帮助。
编辑:我正在运行输出文件,有时它会运行,而其他文件会给我错误。似乎是随机顺序。此外,当我在gdb上运行它时,该程序永远不会失败,它总是正确退出。为什么会这样?
您的限制在初始化代码中被颠倒。您可以像这样创建数组:
this->_vertical = new simpleNode [rows]; // <== uses rows for sizing vertical
this->_horizontal = new simpleNode [cols]; // <== uses cols for sizing horizontal
但是您的初始化是这样做的:
for (i=0; i<this->_rows; i++) // <== limit is rows, but you walking horizontal
this->_horizontal[i]._next = NULL;
for (i=0; i<this->_cols; i++) // <== limit is cols, but you walking vertical
this->_vertical[i]._next = NULL;
除非rows
和cols
是相同的值,否则此代码将调用未定义的行为。通过使用与分配大小相同的值来解决此问题
for (i=0; i<this->_rows; i++)
this->_vertical[i]._next = NULL;
for (i=0; i<this->_cols; i++)
this->_horizontal[i]._next = NULL;
老实说,更好的方法是使用 RAII 容器,例如 std::vector<>
,但我把它留给你一个练习。
祝你好运,希望它有所帮助。
由于你在调试器中,你应该查看内存位置0x7fff7a1d4300
,看看那里有什么。内存中的数据可能有助于找出出了什么问题。
正在发生的事情是以下情况之一:
-
您正在释放一个对象两次,
-
您正在释放从未分配的指针
-
您正在通过一个无效的指针写入,该指针先前指向已释放的对象
我认为发生的事情是第三。
我的回答就是基于这个答案。
这里有一个相关的讨论。
关于GDB的相关问题。
相关文章:
- 不正确的比较和交换计数器输出用于快速排序功能
- 如何用尽可能少的数据将数据缓冲区计算为零校验和值
- 计算校验和的逐位运算符
- 如何从存储在 QByteArray 中的十六进制值计算校验和
- 如何在 c++ 中计算对象的哈希/校验和/指纹?
- C++文件传输的校验和算法
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 如何从 IP 校验和字段中计算十六进制值
- 计算句子的校验和(XOR)(由不同变量/类型的组合形成)
- 目录校验和
- 编译后如何计算某些二进制功能(或基本块)的校验和
- PMS5003带有ESP8266-许多校验和错误
- 未正确的校验和释放对象 - 打印时错误
- 将C++校验和函数转换为 Java
- 确定是否使用boost.asio计算UDP校验和
- 释放对象的校验和不正确
- C++中不起作用的异或校验和算法
- UDP标头校验和不正确时是否丢弃UDP数据包
- c++校验和读取不存在换行符
- 如何为一个简单的C++程序选择正确的校验和,以及如何实现它