未为指针分配分配要释放的指针

pointer being freed was not allocated for pointer assignment

本文关键字:指针 分配 释放      更新时间:2023-10-16

我试图将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是非法的。