内存管理 - C++ 动态声明的数组无法正常工作

memory management - c++ dynamically declared array fails to work

本文关键字:常工作 工作 数组 管理 C++ 动态 声明 内存      更新时间:2023-10-16

我正在尝试使用double *data = new double[14141414]()声明将文件的数据读入动态声明的数组中。 请注意,这是一个相当大的文件;因此数组的大小很大。

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

然而,当我开始将数据放入数组的那一刻,程序会在接近末尾时停止,但在随机位置,有时它会是 14000000,有时索引会多一点,有时会少一点。 有几次程序运行良好。

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

谢谢!!

更新:根据波特的要求 #Jonathan 我在这里包含代码。 谢谢!! 真是个好主意!!

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

省去很多麻烦,请使用vector

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

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

您的"新"内存分配块需要按如下方式更正,不需要在每行末尾()

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];

并且您"删除"块需要更正如下:

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

我认为不正确的删除操作可能是您失败的原因。您为数组分配了内存,但通过使用删除的指针语法而不是使用数组语法来取消分配。

该问题的另一个可能性可能是缺少物理内存,因为根据代码,您正在分配大量内存,而不仅仅是您之前提到的双数组。有一个 std::string 数组等等。

为了更好地避免所有内存分配和取消分配障碍,您可以使用std::vector来代替数组。在您的一条评论中,您通过比较数组和 std::vector 提出了对性能优势的关注。如果你使用编译器优化,(如果在 gcc -O2的情况下),std::vector将与数组相提并论,除非你可能在你的实现中犯了一些严重的错误。