我试图将 ListNode 结构更改为类格式,但在测试它时遇到了一些问题。
获取 a.out(7016) malloc:* 对象 0x7fff65333b10 的错误:正在释放的指针未分配
*在malloc_error_break中设置断点进行调试
chainLink.hpp
#ifndef CHAINLINK_H
#define CHAINLINK_H
using namespace std;
#include <iostream>
#include <cstdlib>
template <typename Object>
class chainLink
{
private:
Object storedValue;
chainLink *nextLink;
public:
//Constructor
chainLink(const Object &value = Object()): storedValue(value)
{
nextLink = NULL;
}
/* Postcondition: returns storedValue;
*/
Object getValue()
{
return storedValue;
}
/* Postcondition: sets storedValue = value
*/
void setValue(Object &value)
{
storedValue = value;
}
/* Postcondition: sets nextLink to &value
*/
void setNextLink(chainLink* next)
{
nextLink = next;
}
chainLink* getNext()
{
return nextLink;
}
~chainLink()
{
delete nextLink;
}
};
#endif
我的测试文件,假设包括
int main()
{
chainLink<int> x(1);
cout << "X: " << x.getValue() << " "<< endl;
chainLink<int> y(2);
cout << "Y: " << y.getValue() << " "<< endl;
chainLink<int>* z = &y;
cout << &y << " " << z << endl;
x.setNextLink(z);
}
输出:
X:1
是:2
0x7fff65333b10 0x7fff65333b10
a.out(7016) malloc:* 对象 0x7fff65333b10 的错误:正在释放的指针未分配
*在malloc_error_break中设置断点进行调试
中止陷阱:6
该错误似乎是由 setNextLink 函数引发的。
非常感谢任何帮助。
你正在给予setNextLink
指向自动分配变量的指针,
x.setNextLink(z); // z points to automatic object y
您尝试在构造函数中删除它。
~chainLink() {
delete nextLink; // attempts to delete automatic object y
}
您需要将指针传递给动态分配的对象,或者创建您自己的 insdechainLink
class.
Note:在 C++ 中,struct
s and class
es 是同一个栏一些差异 https://stackoverflow.com/questions/92859/what-are-the-differences-between-struct-and-class-in-c。可以使用两者中的任何一个来实现等效类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)