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(¤t);
}
++it;
while(it->type != TOKEN_TYPE::CLOSE && it->value != current.value) {
if(it->type == TOKEN_TYPE::OPEN) {
createNode(it, ¤t);
}
++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.
First off, there’s no garbage collection in C++.
Second, use smart-pointers instead of raw pointers:
Third, your assumption is right:
This happens because
currentis allocated in automatic storage.If you manage memory inside
parent, you can create the current node dynamically: