简体   繁体   中英

std::bad_alloc in a c++ vector

I am coping a float processed data to an std vector and I am adding a 0 every 3 values so I could get a frame of 4 values. The size of the vector is less than the maximum data.max_size() = 1 073 741 823. the total size of the vector is data.size()=55 000 000.

The problem is that when I run my App and especially when saving the data to the new vector the app stops automatically and I get std::bad_alloc Error.

Does anyone have an idea about this issue? I am using QTcreator, the app runs in 32bit and I get the processed data from an inherited public class. DATA_getAllMeasurments()[i]->DPacket.DATA_Packet is the data vector.

  void FileGenerate::GeneratePDOfile(uint8 i, std::string  path){

    std::vector <float>data;

    int size = DATA_getAllMeasurments()[i]->DPacket.DATA_Packet.size();
    int newsize= (size *4)/3; 
    unsigned int m =0;
    
    for (int k=0; k<newsize ; k++){
        if (k%4==0)
            data.push_back(0.0);
        else            
            data.push_back(DATA_getAllMeasurments()[i]->DPacket.DATA_Packet[m++]);              
        
    }    
    std::string path2 = path + "/Measurement" +std::to_string(i+1)+".pdo";
    std::ofstream myFile (path2, std::ios::out | std::ios::binary);
    myFile.write((char *)&(data[0]),data.size() *sizeof (float));
    myFile.close();
    data.clear();
    }

The function std::vector::max_size() reports what maximum size is supported by the standard library .

It is evaluated at compile time , and does not report the runtime capabilities of the system your program might be running on.

That said, it is likely that your system did not have enough contiguous memory to allocate the required space. Even if your OS is reporting enough "free space", std::vector is designed to require contiguous space.

By constantly growing your vector, you are fragmenting the addressing space of your process, and in a 32 bit process that is a limited resource.

Fortunately, there is a simple solution - just call data.reserve (new size) before entering your for loop. Chances are, the code will then work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM