【问题标题】:bad_alloc on vector.push() and vector.reserve()vector.push() 和 vector.reserve() 上的 bad_alloc
【发布时间】:2016-07-09 13:15:17
【问题描述】:

我正在尝试构建大小为772538368GLfloat 向量。在执行push_back() 时,我收到bad_alloc 错误。

检查this question 后,我尝试将reserve() 内存用于向量。但是,现在我在尝试 reserve() 本身时遇到了同样的错误。

在我的机器上,vector.max_size: 1073741823,比我需要的要大。其他细节,我在Windows 10上使用VS 2015。也请在下面找到相关代码sn-ps。

我应该怎么做才能解决这个问题?

相关代码sn-p:

int main() {

    vector<GLfloat> targetVector; 
    targetVector.reserve(772538368); //Attempt2 to reserve. Also tried resize()

    vector<vector<vector<GLshort>>> my3DimensionalData;
    //build my3DimensionalData //no problem here.

    //targetVector.reserve(772538368); //Attempt1 to reserve.

    for (GLint rowIndex = 0; rowIndex < numberOfRows; rowIndex++)
    {
        for (GLint colIndex = 0; colIndex < numberOfCols; colIndex++)
        {
            for (GLint depthIndex = 0; depthIndex < numberOfDepths; depthIndex++)
            {
                //perform gymnastic here on my3DimensionalData and get data.

                /*initially I was getting bad_alloc while pushing back  
                 *elements in the following block.
                 *This led to Attempt1 and Attempt2 as shown above.
                 */
                targetVector.push_back(data1);
                targetVector.push_back(data2);
                ...
                targetVector.push_back(data7);
            }
        }
    }
}

【问题讨论】:

  • 什么是sizeof(GLfloat)?您需要sizeof(GLfloat) * 736.75MB 内存用于处理。
  • 您的程序是否编译为 32 位?如果是这样,请更改为 64 位,否则您将永远无法在 32 位模式下创建如此大的数组。
  • 关于std::vector::max_size,“在运行时,容器的大小可能会被限制为小于 max_size() 的值,这取决于可用的 RAM 量。”

标签: c++ vector bad-alloc


【解决方案1】:

您很可能需要 64 位版本。您需要超过 3 GB 的连续内存,而这几乎是 4GB 内存空间的全部。

【讨论】:

  • 虽然这很明显,但我不得不提到在 64 位操作系统上运行是不够的。您还需要针对 64 位进行编译(正如这个答案所暗示的那样)。
猜你喜欢
  • 2013-03-20
  • 2010-12-08
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多