释放的指针未分配给指针分配 [英] pointer being freed was not allocated for pointer assignment
问题描述
我试图将ListNode结构更改为类格式,但是在测试它时遇到了一些问题.
I was trying to change a ListNode struct into a class format but am running into some issues when testing it.
获取a.out(7016)malloc: *对象0x7fff65333b10的错误:未分配正在释放的指针 * 在malloc_error_break中设置一个断点以进行调试
Getting a.out(7016) malloc: * error for object 0x7fff65333b10: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug
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
我的测试文件,假设包含
My test file, assume includes
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中设置一个断点以进行调试 中止陷阱:6
OUTPUT: X: 1 Y: 2 0x7fff65333b10 0x7fff65333b10 a.out(7016) malloc: * error for object 0x7fff65333b10: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6
setNextLink函数似乎引发了错误.
The error seems to be thrown by the setNextLink function.
任何帮助都将不胜感激.
Any help greatly appreciated.
推荐答案
您正在给setNextLink
指向自动分配的变量的指针
You are giving setNextLink
a pointer to an automatically allocated variable,
x.setNextLink(z); // z points to automatic object y
您尝试在构造函数中删除的
.
which you attempt to delete in the constructor.
~chainLink() {
delete nextLink; // attempts to delete automatic object y
}
您需要将指针传递给动态分配的对象,或者将自己的insde插入您的chainLink
类.
You need to pass a pointer to a dynamically allocated object, or make your own insde your chainLink
class.
注意:在C ++中,struct
s和class
es是同一栏
Note: In C++, struct
s and class
es are the same bar some differences. A equivalent types can be implemented using either of the two.
这篇关于释放的指针未分配给指针分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!