I was trying to write a n-ary tree,each node contains 4 elements,1 vecter<Node*>,3 variable.
When I try to assign the value by pointer,I found the value will be covered by the after value.
I think may be because the pointer point to each value,so all the value will be the same.So I try to set the pointer to NULL,but it still didn't work.
#include <string.h>
#include <vector>
#include <iostream>
using namespace std;
struct Node{
vector<Node*> subNodes;
bool isFile=0;
bool isDir=0;
int value=0;
};
int main()
{
Node* rootNode_ptr;
Node rootNode;
rootNode_ptr =&rootNode;
rootNode_ptr->value=99;
for(int i=0;i<5;i ){
Node* subNode_ptr;
Node subNode;
subNode_ptr=NULL;
subNode_ptr = &subNode;
subNode_ptr->value=i;
rootNode_ptr->subNodes.push_back(subNode_ptr);
cout<<"0 : "<<rootNode_ptr->subNodes[0]->value<<endl;
cout<<rootNode_ptr->subNodes[i]->value<<endl;
}
return 0;
}
the subNodes[0].value keeps changing
CodePudding user response:
The variables declared in a for loop are on the stack. The moment they go out of scope (such as, say, your loop repeats, or the loop terminates) then the variables are destroyed. Storing pointers to destroyed objects causes undefined behavior when you read from them. You need the objects to persist longer. The most obvious way is to allocate them on the heap (perhaps by using the "new" operation, or std::make_unique()), and they won't go away until you delete them (or the unique_ptr goes out of scope.)
Setting a pointer to null before assigning to it is not going to help.
So instead of this:
Node* subNode_ptr;
Node subNode;
subNode_ptr=NULL;
subNode_ptr = &subNode;
subNode_ptr->value=i;
Try this: Node subNode_ptr = new Node; subNode_ptr->value = i;
And be sure to clean it up later. Your node's destructor needs to iterate the vector and delete each element. Also, you also need to worry about copying and assigning one Node to another, because the vector of pointers needs to do a deep copy. (Since the nodes "think" they own the pointed-to objects, if two both point to the same object and one is later destroyed it will delete the object. Then the remaining copy will try to use it and UB happens.)