Arpad Toth

Programming Addict

The dangerous pointer to vector

November 24, 2015

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:

#include 
#include 

int main()
{
    std::vector intVector;
    intVector.push_back(1);
	
    // We get the pointer to the first element from our vector.
    int* pointerToInt = &intVector[0];
    std::cout << "The value of our int is: " << *pointerToInt << std::endl;
	
    // Add two more elements to trigger vector resize. During
    // resize the internal array is deleted causing our pointer
    // to point to an invalid location.
    intVector.push_back(2);
    intVector.push_back(3);
    std::cout << "The value of our int is: " << *pointerToInt << std::endl;

    return 0;
}

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.

I'm a Software Developer with 10+ years of experience, indie Android App Developer, Co-Founder at Interactions Lab, makers of AgroGo who loves playing guitar, hiking and ocasionally writing on this blog.