问题描述
vector<int> v;
v.push_back(1);
int * p = &v[0];
for (int i = 2; i <= 100; ++i)
{
v.push_back(i);
}
*p = 5;
我知道vector重新分配了一块新的内存以增加容量,但是p只是指向某个内存地址的指针,而p本身并没有改变.即使向量重新分配后,p所指向的内存也位于同一进程的地址空间中.为什么会崩溃?
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?
推荐答案
如果将代码更改为以下内容:
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;
}
您将看到&v[0]
的内存地址几乎总是与重新分配之前的地址不同.这意味着您创建的指针现在指向(潜在地)无效的内存.
现在,您只有一个指针p
指向某个内存块.无法保证该内存块中的内容,即使它是有效的.
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.
这篇关于指向矢量元素的指针崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!