我试图将 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 Y:2 0x7fff65333b10 0x7fff65333b10 a.out(7016) malloc:* 对象 0x7fff65333b10 的错误:未分配被释放的指针 *在 malloc_error_break 中设置断点以调试 Abort 陷阱:6
该错误似乎是由 setNextLink 函数引发的。
非常感谢任何帮助。