AlexSavAlexandrov
AlexSavAlexandrov

Reputation: 873

Pointer pointing to an element in a vector gets set to NULL when the structure grows

A pointer to an object gets set to NULL, despite the fact that there is no pointerToObj = NULL anywhere in the function. Later I use that pointer for something and it causes an Access Violation exception. I also added a test pointer to see if it will preserve its value, but no - both get set to NULL at the same time.

The pointer points at an object in a vector. At one point, I add a new object to the vector, so the structure grows. Right after this the pointer gets set to NULL. I tested this - all pointers, that point to a certain element of the vector, get set to NULL right after I add the new object.

I suspect that this happens because of the way the Vectors work - if I am not mistaken, they are based on a Stack. When a stack has to lengthen itself, it must copy itself in a new bigger array and delete the old one. But now the new array is located elsewhere in the memory, so my pointer is no longer pointing in the correct location.

Is this really the case?

Upvotes: 0

Views: 653

Answers (2)

Yousef Eldaly
Yousef Eldaly

Reputation: 11

Using std::vector to store pointers or objects that have pointer members resets all the pointers to the new vector allocated memory addresses-NULL or any memory address. You can set the pointer to the value you want after you push it back in the vector instead of setting it before push_back(). For Example, if you have an object called x of class client that has pointers, and you want to store it in vector v. Do this:

client x;
v.push_back(x);
static int i = 0;
v[i++].set_name();

So, if you called v[i].get_name() the pointer will be pointing on the name.

Instead of:

client x;
x.set_name();
v.push_back(x);
x.get_name();

This will return a random memory address.

Be carful, every time you push_back() an element the vector size is doubled, and the first element pointer will point to a new location that fits the doubled size. You can set the first element to a garbage or empty object of type client, or you can reserve vector memory before you do anything with it in order to keep all the addresses as they are. You can see how this is done here: change of vectors first pointer.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

Yes, adding an element to a std::vector may invalidate pointers to its elements for the reason you describe (but it doesn't have anything to do with stacks). Your pointer isn't being magically set to null though, it just points at a non-existent object.

Upvotes: 3

Related Questions