3

我试图将 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 函数引发的。

非常感谢任何帮助。

4

3 回答 3

1

在您的最后一行中,mainsetNextLink使用指向具有自动存储持续时间的对象的指针进行调用(z保存地址y)。您的列表在销毁时尝试删除该指针,因此错误(y尚未动态分配,因此无法动态删除)。

于 2012-09-04T06:34:40.797 回答
1

您正在给出setNextLink一个指向自动分配变量的指针,

x.setNextLink(z); // z points to automatic object y

您尝试在构造函数中删除它。

~chainLink() {
    delete nextLink; // attempts to delete automatic object y
}

您需要将指针传递给动态分配的对象,或者让您自己的 insdechainLink类。

注意:在C++中,structs和classes是一样的吧有些区别。可以使用两者中的任何一个来实现等效类型。

于 2012-09-04T06:35:07.910 回答
0

后线x.setNextLink(z); x.nextLink指向z,后者又指向y。而是y一个局部对象。它分配在堆栈上而不是堆上。所以调用它是违法的delete

于 2012-09-04T06:42:23.380 回答