Lerp
Lerp

Reputation: 3127

Preventing pointer from pointing to nothing

I am having trouble preventing objects that my pointers are pointing from being freed. I think this is the problem but I do not know how to resolve it.

My code:

enum TOKEN_TYPE {
    OPEN, CLOSE, TEXT
};

struct Token {
    int type;
    std::string value;
};

typedef std::vector<Token>::iterator token_it;

Tree::Tree(token_it start) {    
    root.value = start->value;
    createNode(++start, &root);
}

void Tree::createNode(token_it it, Node* parent) {
    Node current;

    current.value = it->value;
    current.parent = parent;

    if(parent != 0) {
        parent->children.push_back(&current);
    }

    ++it;
    while(it->type != TOKEN_TYPE::CLOSE && it->value != current.value) {
        if(it->type == TOKEN_TYPE::OPEN) {
            createNode(it, &current);
        }

        ++it;
    }
}

I tried stepping through the program and everything's perfect until the end when the program begins to exit the createNode calls where garbage collection frees current which leaves parent pointing to nothing; at least that is what I think is happening.

Upvotes: 2

Views: 171

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258568

First off, there's no garbage collection in C++.

Second, use smart-pointers instead of raw pointers:

void Tree::createNode(token_it it, SmartPtr<Node> parent)

Third, your assumption is right:

{
   Node current;
   parent->children.push_back(&current);
} //current is destroyed here

This happens because current is allocated in automatic storage.

If you manage memory inside parent, you can create the current node dynamically:

{
   Node* current = new Node;
   parent->children.push_back(current);
} 

Upvotes: 3

Related Questions