开发者

Members of structs and pointers, C++

I have the following snippet of code:

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;

    }

The problem I'm having is that thing2->data = "f" is producing a segmentation fault during runtime. I've run the program through GDB and get this error, but I can't figure out w开发者_高级运维hat it means:

Reading symbols for shared libraries ++. done Thing data = h

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: 13 at address: 0x0000000000000000 0x00007fff874d59a3 in std::string::assign ()

Any help would be great. Thanks!


thing2 is a non initialized pointer. It doesn't point to a valid Node object.

You should allocate it:

thing2 = new Node;

or make it point to a valid Node object:

thing2 = & thing;


thing2 is a pointer to a Node, but you haven't made it point to anything:

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

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

The above code allocates a Node on the heap, assigning it to thing2. When it's done with the object, it deletes it.

A more idiomatic approach is to use a smart pointer:

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

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

Since auto_ptr's destructor deletes whatever it is pointing at, you don't need to explicitly delete the object.


thing2 is declared as a pointer, and you never allocate (via new, malloc, or even on the stack) the actual node to which that pointer will point. Thus, node2 points to some unknown bit of memory apparently outside of your program's address space, and when you attempt to modify that memory via the thing2->data = "f" call the OS rightly protects itself (and you) by disallowing it. That's what the seg. fault is all about.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜