C++动态声明的数组无法工作

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

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

问题是我无法将所有数据放入一个数组中,因为在 index=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

最佳答案

使用 vector

为自己省去很多麻烦
std::vector<double> data;
data.reserve(SIZE_OF_ARRAY); // not totally required, but will speed up filling the values

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

关于C++动态声明的数组无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812503/

相关文章:

c++ - 将类转换为结构

java - 如果我将 max -Xmx2048m 内存分配给具有 2GB RAM 的 64 位 Linux 机器的 Java 进程,会发生什么情况?

ios - 通过导航 Controller 调用自定义加载方法

c++ - 编译器内存优化 - 重用现有 block

javascript - new 和 instanceof Javascript

c++ - 如何在两个不同的函数c++中访问动态数组

c++ - Win32 API : How to clip siblings using GetDCEx()?

c++ - 如何实现一致的方法来检测鼠标按钮是否被按住

c# - 如何将List<List<Int32>>的初始化简化为IEnumerable<IEnumerable<Int32>>?

c++ - 运算符 new[] 不接收额外的字节