pointer to a vector element crashes

只愿长相守 提交于 2019-12-20 03:37:41

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!