Search code examples
c++vectorbad-alloc

bad_alloc on vector.push() and vector.reserve()


I am trying to build a vector of GLfloat of size 772538368. While doing push_back() I am getting bad_alloc error.

After checking this question, I tried to reserve() memory for the vector. However, now I am getting the same error on the attempt of reserve() itself.

On my machine, vector.max_size: 1073741823, which is bigger than what I need. In other details, I am using VS 2015 on Windows 10. Also please find the relevant code snippets below.

What should I do to resolve this?

Relevant code snippet:

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);
            }
        }
    }
}

Solution

  • You're most likely going to need a 64 bit build. You need over 3 GB of contiguous memory, and that is almost all of your 4GB memory space.