vendredi 5 novembre 2021

C++: Will my pointer be dangling? How to assign a pointer a variable that exists in a function?

Im having difficulty describing this problem succinctly so be kind.

I have a Tree object that has an attribute root which is a pointer to a node object. When I initialize the Tree object the root is unknown so i assign it to a nullptr.

In a function after some computation I find the root node of a complete binary tree. I now want to hand this value over to my Tree.root pointer. However since this function is removed from the stack after execution and Tree.root pointer appears empty when I run it later.

class Tree{
    public:
        Node *root;
        Tree(){
            root = nullptr;
        }
};
void worker(Tree *t){
    // Perform some computation



// Since the var rootFound only exists in this function. 
// After executing doesn't the memory address reallocated 
// and therefore the root points to an unknown memory address?
    t-> root = &rootFound;

}
int main(){
    Tree t{};
    Tree *ptr = &t;
    worker(t);
//    t pointer is null
    return 0;
}

I was thinking I could assign the root pointer found by the function to the heap (use new ) and then assign my Tree pointer to it but Im not sure how to go about deleting this value. Also since any node has left and right Node pointer Im not sure if the pointers lose the memory address they are pointing too or if they too will be added to the heap.

I could also just be overthinking this.

Aucun commentaire:

Enregistrer un commentaire