c ++动态声明的数组无法正常工作

Jav*_*Fan 1 c++ theory memory-management heap-memory new-operator

我试图使用double *data = new double[14141414]()声明将文件的数据读入动态声明的数组.注意,它是一个大文件; 因此阵列的大小.

问题是我无法将所有数据放入数组中,因为索引= 14000000左右执行只会停止.
代码编译得很好(没有错误).我做了调试,并new返回一个地址,而不是0或NULL.所以看起来内存分配没有问题(即内存不足).我甚至在没有数组分配的情况下将文件回显到屏幕,只是为了看到我能够很好地读取文件.一切看起来都不错

然而,当我开始将数据放入数组时,程序将停止接近结束但是在随机位置,有时它将是1400万,有时索引会稍微多一些,有时会少一点.有几次程序运行良好.

有人知道发生了什么吗?我怀疑计算机耗尽了物理内存,从而导致程序的这种行为.但如果是这样,那么为什么new运营商会返回一个地址呢?如果内存分配失败,它应该返回0还是NULL?

谢谢!!

更新:根据#Jonathan Potter的要求,我在这里包含了代码.谢谢!!真不错的主意!!

void importData(){

int totalLineCount = 14141414;

double *height = new (nothrow) double[totalLineCount]();
int *weight = new (nothrow) int[totalLineCount]();
double *pulse = new (nothrow) double[totalLineCount]();
string *dateTime = new (nothrow) string[totalLineCount];
int *year = new (nothrow) int[totalLineCount]();
int *month = new (nothrow) int[totalLineCount]();
int *day = new (nothrow) int[totalLineCount]();

fstream dataFile(file.location.c_str(), ios::in);
for (int i = 0; i < totalLineCount; i++) {      
  dataFile >> weight[i] 
      >> height[i] 
      >> pulse[i]
      >> year[i] 
      >> dateTime[i]; 
  } //for
dataFile.close();

delete height;
delete weight;
delete pulse;
delete dateTime;
delete year;
delete month;
delete day;

}//function end
Run Code Online (Sandbox Code Playgroud)

twe*_*mon 6

为自己省去麻烦,使用一个 vector

std::vector<double> data;
data.reserve(SIZE_OF_ARRAY); // not totally required, but will speed up filling the values
Run Code Online (Sandbox Code Playgroud)

vector将为您提供更好的调试消息,您不必自己处理内存.