问题
vector<int> v;
v.push_back(1);
int * p = &v[0];
for (int i = 2; i <= 100; ++i)
{
v.push_back(i);
}
*p = 5;
I know vector reallocated new piece of memory to increase capacity, but p is just a pointer to some memory address and p itself didn't change. Also memory pointed to by p is in the address space of the same process even after the vector reallocates. Why would it crash?
回答1:
If you change your code to the following:
#include <stdio.h>
#include <vector>
int
main(int argc, char* argv[])
{
std::vector<int> v;
v.push_back(1);
int * p = &v[0];
printf( "Old: %08X\n", &v[0] );
for (int i = 2; i <= 100; ++i)
{
v.push_back(i);
}
printf( "New: %08X\n", &v[0] );
getchar();
return 0;
}
You will see that the memory address of &v[0] is almost always different to what it was before the reallocation. That means the pointer you created is now pointing to (potentially) invalid memory.
You now just have a pointer p pointing to some block of memory. There are no guarantees as to what is in that block of memory, or even if it is valid.
来源:https://stackoverflow.com/questions/32490972/pointer-to-a-vector-element-crashes