Skip to content

Instantly share code, notes, and snippets.

@arpytoth
Created November 24, 2015 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arpytoth/f8a43578f39de7ab378e to your computer and use it in GitHub Desktop.
Save arpytoth/f8a43578f39de7ab378e to your computer and use it in GitHub Desktop.
The dangerous pointer to vector
#include <iostream>
#include <vector>
int main()
{
std::vector<int> 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment