c++ - 大 vector 上的 .push_back() 会导致 std::bad_alloc

标签 c++ heap-memory bad-alloc

这是在 64 位 VS C++ 2015 上编译的。std::bad_alloc 发生在 x 特别是 1120 的地方

static std::vector<std::vector<std::vector<double>>> g_damagefunction;
static std::vector<std::vector<double>> g_has_damagefunction;
static std::vector<double> null_v_double;
static std::vector<bool> null_v_bool;
static std::vector<std::vector<double>> null_vv_double;
int main(){
for (int x = 0; x < 4400; x++) {
    std::cout << x << '\n';
    g_damagefunction.push_back(null_vv_double);
    g_has_damagefunction.push_back(null_v_bool);

    for (int y = 0; y < 2000; y++) {
        g_damagefunction[x].push_back(null_v_double);
        g_has_damagefunction[x].push_back(false);
        for (int i = 0; i < 41; i++) {
            g_damagefunction[x][y].push_back(0.0);
        }
    }
}
}

最佳答案

bad_alloc 这里意味着你的内存不足。 g_damagefunction vector 中的 double 元素的大小将占用 (4400 x 2000 x 41 x sizeof(double)) 字节,相当于大约 2.68 GB 的内存。如果加上 vector 本身占用的内存量,您可以清楚地看到计算机的 RAM 不足以满足程序的要求,或者程序使用了太多内存。我怀疑是后者。

关于c++ - 大 vector 上的 .push_back() 会导致 std::bad_alloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963193/

相关文章:

c++ - 无效的 int 输入陷入无限循环

c++ - 跟踪在 C++ 中调用递归函数的次数

java - Tomcat 6 堆大小 - 这是正确的吗?

c++ - SetClipboardData() 期间的堆损坏

c++ - 声明 new int[n] 时的 std::bad_alloc

c++ - 将数百万个对象插入 Vector = bad-alloc

c++ - 分配新 vector 时的 std::bad_alloc - 我能做什么

c++ - 如何识别导致简单应用程序在 Windows 中崩溃的原因? (应用程序在 Visual Studio 中编译成功 + 帖子中出现完整错误)

c++ - 在这种情况下如何使模板类型推断起作用?

c - 堆栈上的变量是 "statically allocated"吗?