【问题标题】:std::bad_alloc when concatenating two vectors连接两个向量时的 std::bad_alloc
【发布时间】:2016-05-03 15:11:03
【问题描述】:

我在连接 2 个向量时遇到了一些问题。

std::vector<Transform3D> out;
for(double theta = 0; theta <= 2*M_PI ; theta+=1 )
{
    for(double phi = 0; phi <= M_PI ; phi+=1 )
    {
        double sphere_x = obj_x + r*cos(theta)*sin(phi);
        double sphere_y = obj_y + r*sin(theta)*sin(phi);
        double sphere_z = obj_z + + r*cos(phi);
        Transform3D<> transformation_matrix = transform(obj_x,obj_y,obj_z,sphere_x,sphere_y,sphere_z);

        if(0.01<(transformation_matrix.P()[0] - current_x) ||
            0.01<transformation_matrix.P()[1] - current_y ||
            0.01<transformation_matrix.P()[2] - current_z)
        {
            cout << "Interpolate: " << endl;
            std::vector<Transform3D> transformation_i = invKin_LargeDisplacement(transformation_matrix);

            out.insert(out.end(),transformation_i.begin(),transformation_i.end());
        }
        else
        {
            cout << "OK" << endl;
            out.push_back(transformation_matrix);
        }
        cout << out.size() << endl;
        cout << sizeof(Transform3D<>) << endl;
    }
}

out.insert(..) 似乎会导致bad_alloc,但需要额外的数据。

在调试问题时,我在运行 for 循环时打印了向量的大小并得到以下输出:

Interpolate: 
6346700
Interpolate: 
12052200
Interpolate: 
16476100
Interpolate: 
20127501
Interpolate: 
26474201
Interpolate: 
32239601
Interpolate: 
36748301
Interpolate: 
40416502
Interpolate: 
46763202
Interpolate: 
52659402
Interpolate: 
57349102
Interpolate: 
61053903
Interpolate: 
67400603
Interpolate: 
73377503
Interpolate: 
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

有什么方法可以避免获得bad_alloc,同时仍然能够进行插值?

【问题讨论】:

  • 您的内存不足。是时候看看哪里可以减少内存使用了。
  • 我还没用过swap..
  • 7300 万个对象可能是很多内存。 sizeof(rw::math::Transform3D&lt;&gt;) 是什么?
  • 您的实际 RAM 与进程的虚拟空间无关。另外,它是 32 位还是 64 位可执行文件?
  • @Lamda 不要忘记,如果向量被调整大小,那么您需要分配 2 块内存才能复制,这或可能确实发生了。您有来自向量的旧块和将所有内容复制到的新块。大约有 13 GB 的内存,加上你有临时向量和系统上运行的任何其他东西。

标签: c++ vector


【解决方案1】:

如果我们假设您的变换是一个具有 4x4 浮点数组(4 个字节)的 PoD:

变换大小 = 4*4*4 = 64 字节
异常时数组的大小 = 73377503

64 * 73377503 = 4696160192 字节 = 4.696160192 GB

有了这么大的向量,我希望你的内存用完了......

你的机器有多少内存,你真的需要 4.7Gb 的转换数据吗?

如果是这样,也许可以考虑压缩内存中的数据和/或将其写入文件缓存。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2014-05-29
    • 2011-03-30
    • 1970-01-01
    • 2016-06-17
    • 2010-09-17
    • 1970-01-01
    相关资源
    最近更新 更多