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

时间:2015-06-12 21:33:39

标签: c++ memory-management new-operator theory heap-memory

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

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

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

有人知道发生了什么吗?我怀疑计算机耗尽了物理内存,从而导致程序的这种行为。但如果是这样,那么为什么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

2 个答案:

答案 0 :(得分:6)

为您节省大量麻烦,请使用vector

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

vector会为你提供更好的调试信息,你不必自己处理内存。

答案 1 :(得分:1)

您的“新”内存分配块需要更正如下,每行末尾不需要()

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 -O2std::vector将与数组相同,除非您在实现中犯了一些严重错误。