我试图将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);
}
OUTPUT: X:1 Y:2 0x7fff65333b10 0x7fff65333b10 a.out的(7016)的malloc:*误差对象0x7fff65333b10:被释放指针没有被分配 *设置在malloc_error_break断点调试 中止陷阱:6
的误差似乎是由setNextLink功能抛出。
任何帮助非常感谢。
如果您尝试阅读并理解错误消息告诉您的内容,它会有所帮助:“指针被释放**未分配**”。这可能意味着你忘了分配一些东西,比如在某处说'new'。每个'delete'调用都必须在某个地方有一个'new'调用(可能或者可能不在你的代码之外)。 –
你是否从通话中获得了'z'指针? – Mat
不是严格相关的,但是通过改变“从结构到类格式”是什么意思? – jalf