为什么在运行我的代码后显示 bad_alloc 消息

问题描述

代码显示消息“在抛出 'std::bad_alloc' 实例后调用终止 what(): std::bad_alloc

进程返回 3 (0x3) 个执行时间:0.331 秒" 我无法确定的问题在哪里。我使用了代码块。我的电脑内存是 8GB。

#include <iostream>
#include<vector>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <sstream>

using namespace std;

int main(){

ofstream bcrs_tensor;
bcrs_tensor.open("bcrs_tensor_Binary",ios::out | ios::binary);

int X=6187,Y=25,Z=78,M=33;



int new_dimension_1,new_dimension_2,new_x_1,new_x_2;
new_dimension_1=X*Z;
new_dimension_2=Y*M;

int* new_A = new int[ new_dimension_1*new_dimension_2 ];

vector<int> block_value,CO_BCRS,RO_BCRS;
block_value.reserve(303092010);
CO_BCRS.reserve(1554318);
RO_BCRS.reserve(37124);
cout<<"size"<<sizeof(block_value)<<endl;
return 0;
}

解决方法

您正在尝试分配比系统可用于您的应用更多的内存,因此 std::bad_alloc 被抛出,而您没有捕捉到。

假设在您的编译器中使用 sizeof(int)=4,您要求:

  • 1.48GB new_A
  • 1.12GB block_value
  • 5.92MB CO_BCRS
  • 145KB RO_BCRS

总共2.61GB

即使您安装了 8GB 的​​ RAM,您的系统也没有足够的连续内存来满足这些分配之一(即,如果它是 32 位应用程序,则整个过程仅限于最大 2-3GB,具体取决于配置、内存管理器实现等。但其中很大一部分是由操作系统本身保留的,您不能将其用于您的代码)。