Home > OS >  Pushing non dynamically allocated objects to a vector of pointers
Pushing non dynamically allocated objects to a vector of pointers

Time:06-23

I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck.

So basically I have the following code inside a function:

Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);

and the following struct:

struct Node{
    int data;
    vector<Node*> adj;
};

When I do the push_back to the vector the program just cycles for 2-3 seconds and exits with a non-zero exit code. If I allocate the memory dynamically It seems to work correctly. Does the program somehow blow up when the pointer is not pointing to a specific block of memory?

CodePudding user response:

"Traversing" pointers that are not pointing at objects is undefined behavior in C .

The pointer doesn't have to point at a dynamically allocated object, but that is typical. The pointer could point at an automatic storage object. For example:

Node bob;
Node* root = &bob;

however, in every case, you are responsible for managing lifetime of these objects. Automatic storage objects survive until the end of the current scope, temporary objects until the end of the current full expression, and dynamically allocated objects until they are deleted.

Smart pointers can help a bit with lifetime management issues, but they only help. They do not solve it, and you still have to be aware of lifetime.

Many post-C languages have automatic garbage collection that makes lifetime less of the programmers problem. You do not have this help in C .

  • Related