未为指针分配分配要释放的指针
pointer being freed was not allocated for pointer assignment
我试图将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: 1Y: 20x7fff65333b10 0x7fff65333b10a.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
}
你需要传递一个指向动态分配对象的指针,或者使你自己的 insde 成为你的 chainLink
类。
注意:在C++中,struct
s 和 class
es 是相同的,但有一些差异。可以使用两者中的任何一个实现等效类型。
在
main
的最后一行中,您将使用指向具有自动存储持续时间的对象的指针调用setNextLink
(z
保存y
的地址(。您的列表在销毁该指针时会尝试删除该指针,因此会出现错误(y
尚未动态分配,因此无法动态删除(。
行后 x.setNextLink(z);
x.nextLink
指向 z
,而 又指向 y
。但y
是一个本地对象。它是在堆栈上分配的,而不是在堆上分配的。因此,打电话给delete
是非法的。
相关文章:
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 我似乎无法为指针分配一个数组,然后更改数组的内容
- C++为 void 指针分配一个字符串
- 当我在 C++ 中将派生类的指针分配给指针时,地址会更改
- MPI 集合通信中的指针分配
- 函数指针分配在创建 DLL 后导致错误
- 通过双指针分配指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 我可以直接为指针分配地址吗?如果是,如何做到这一点
- 为什么为char指针分配内存不会截断char序列
- C++指针分配字符数组的地址
- 将 void 指针分配给另一个 void 指针
- 如何将不同的成员函数指针分配给注册类的不同实例?
- 如何为指针分配特定的内存地址?
- C++ - 无法将顶部常量指针分配给另一个非常量指针
- 将指针分配给另一个指针时会发生什么情况?
- 为指向C++中的对象/对象的指针分配堆内存
- 将指针分配给字符串变量中包含的地址
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用