2012-09-04 65 views
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); 
} 

OUTPUT: X:1 Y:2 0x7fff65333b10 0x7fff65333b10 a.out的(7016)的malloc:*误差对象0x7fff65333b10:被释放指针没有被分配 *设置在malloc_error_break断点调试 中止陷阱:6

的误差似乎是由setNextLink功能抛出。

任何帮助非常感谢。

+4

如果您尝试阅读并理解错误消息告诉您的内容,它会有所帮助:“指针被释放**未分配**”。这可能意味着你忘了分配一些东西,比如在某处说'new'。每个'delete'调用都必须在某个地方有一个'new'调用(可能或者可能不在你的代码之外)。 –

+0

你是否从通话中获得了'z'指针? – Mat

+0

不是严格相关的,但是通过改变“从结构到类格式”是什么意思? – jalf

回答

1

你给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是相同的条some differences。可以使用两者中的任何一种来实现等效类型。

1

main您正在使用一个指针调用setNextLink与自动存储持续时间的对象的最后一行(z持有y的地址)。您的列表试图在销毁该指针时删除该指针,因此错误(y尚未动态分配,因此无法动态删除)。

0

线x.setNextLink(z);x.nextLinkz,这反过来又指向y后。但是y本地对象。它被分配在栈上而不是堆上。因此,拨打delete是非法的。