内存管理 - C++ 动态声明的数组无法正常工作
memory management - c++ dynamically declared array fails to work
我正在尝试使用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
将与数组相提并论,除非你可能在你的实现中犯了一些严重的错误。
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- C++程序已停止工作-求解常微分方程