2010-11-06 51 views
0

我有下面的代码片断:成员,C++

struct Node 
{ 
    Node* left; 
    Node* right; 
    string data; 
};  

void test() 
    { 
     Node thing; 
     thing.data = "h"; 
     thing.left = NULL; 
     thing.right = NULL; 

     cout<< "Thing data = " << thing.data << endl; 

     Node* thing2; 
     thing2->data = "f"; 
     thing2->left = NULL; 
     thing2->right = NULL; 

     cout<< "Thing2 data = " << thing2->data << endl; 

    } 

时遇到的问题是,thing2->数据=“f”被生产运行期间分割故障。我已经通过GDB运行该程序,并得到这个错误,但我无法弄清楚它是什么意思:

阅读共享库++的符号。完成 数据= h

程序接收信号 EXC_BAD_ACCESS,无法访问 内存。原因:13地址: 性病0x0000000000000000 0x00007fff874d59a3 ::字符串::分配()

任何帮助将是巨大的。谢谢!

+0

* facepalm *我不知道我和我的朋友可以如何忽视这个问题。感谢您的反馈。当这个时间限制解除后,我会接受一个答案。 – vince88 2010-11-06 01:45:39

回答

2

thing2是一个非初始化指针。 它不指向有效的节点对象。

您应该分配它:

thing2 = new Node; 

或使其指向有效的Node对象:

thing2 = & thing; 
1

thing2是一个指向Node,但是你有没有使它指向任何东西:

Node* thing2 = new Node; 
    thing2->data = "f"; 
    thing2->left = NULL; 
    thing2->right = NULL; 

    cout<< "Thing2 data = " << thing2->data << endl; 
    delete thing2; 

上面的代码分配一个节点上堆,将其分配给thing2。当它完成对象时,它将删除它。

更惯用的方法是使用一个智能指针:

#include <memory> 
... 
    std::auto_ptr<Node> thing2(new Node); 
    thing2->data = "f"; 
    thing2->left = NULL; 
    thing2->right = NULL; 

    cout<< "Thing2 data = " << thing2->data << endl; 

由于auto_ptr的析构函数删除不管它是在指指点点,你并不需要显式删除对象。

1

thing2被声明为指针,你永远不分配(通过新的malloc,甚至在堆栈上)该指针将指向的实际节点。因此,节点2明显地指向程序地址空间之外的某些未知内存位置,并且当您尝试通过thing2->data = "f"调用修改该内存时,操作系统会通过禁止它来正确保护自己(和您)。这就是seg。故障是全部。