带有 push_back 的 libstdc++ 错误复制 vecor 元素

问题描述

我在下面的小程序中遇到了以下错误:

#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<int> t;
    t.push_back(0);
    for(int i = 1; i < 1024; i++) {
        auto& x = t[i-1];
        t.push_back(x);
        t.push_back(x);
        t.push_back(x);
    }
    return 0;
}

它编译得很好并且执行时没有任何错误。但是如果你用 valgrind 运行它(Linux 机器),你会得到一个内存错误:

==122572== Invalid read of size 4
==122572==    at 0x10A051: void __gnu_cxx::new_allocator<int>::construct<int,int const&>(int*,int const&) (in /home/casse/tmp/bug)
...

现在,如果你稍微修改一下上面的代码:

auto x = t[i-1];

(不是获取引用,而是从向量中复制元素),valgrind 不再抱怨。

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)