The dangerous pointer to vector

This is actually a really obvious “issue” but I found that some developers (usually the inexperienced ones) simply don’t think about this horrible source of bugs:). Now let’s see the problem:

If you run the code snipped above you will see an output similar to:

The value of our int is: 1
The value of our int is: -572662307

The explanation for this is simple. If you think that is a great idea to hold pointers to vector elements, you are wrong. The vector is basically a resizable array and the actual resize operation is:

  • Create a new and bigger array.
  • Copy all content from the current array to the newly allocated array.
  • Delete the current array and replace it with the newly created array.

See the problem? When the resize occurs, the underlying array is deleted and your pointer is invalidated. So be careful and don’t use pointer to vectors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s