指向向量元素的指针崩溃 [英] pointer to a vector element crashes

查看:15
本文介绍了指向向量元素的指针崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    vector<int> v;
    v.push_back(1);
    int * p = &v[0];
    for (int i = 2; i <= 100; ++i)
    {
        v.push_back(i);    
    }
    *p = 5;

我知道向量重新分配了一块新的内存来增加容量,但是 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
", &v[0] );
    for (int i = 2; i <= 100; ++i)
    {
        v.push_back(i);    
    }
    printf( "New: %08X
", &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.

这篇关于指向向量元素的指针崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆