1

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);
            }
        }
    }
}
Community
  • 1
  • 1
Sayan Pal
  • 4,768
  • 5
  • 43
  • 82
  • 3
    What is `sizeof(GLfloat)`? You need `sizeof(GLfloat)` * 736.75MB memory for the processing. – songyuanyao Jul 09 '16 at 13:18
  • 3
    Is your program compiled as 32-bit? If so, change to 64-bit because otherwise you won't ever be able to create such a big array in 32-bit mode. – milleniumbug Jul 09 '16 at 13:19
  • 2
    About [`std::vector::max_size`](http://en.cppreference.com/w/cpp/container/vector/max_size), "At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available." – songyuanyao Jul 09 '16 at 13:22

1 Answers1

3

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 1
    While it may be obvious, I'm compelled to mention that running on a 64-bit OS isn't sufficient. You also need to compile for 64-bits (as this answer suggests). – IInspectable Jul 09 '16 at 13:26