在C ++中读取大的.txt文件时出现奇怪的错误 [英] Weird error when reading a large .txt file in c++
问题描述
我正在尝试读取一个非常大的.txt文件,该文件具有128x128x128 = 2097152行(线性化的3d空间),每行仅包含一个0或1(不要问为什么)...我将代码缩减为几行,似乎当我确定行和增量时,一切进展顺利...但是,只要我想将数据放入足够允许的数组中,行读取就会在i = 12286处停止...
i'm trying to read a very large .txt file that has 128x128x128=2097152 lines (linearised 3d space) containing only one 0 or 1 by line (Don't ask why)... I mowed down my code to a few lines and it seems that when I cout the line and the increment, everything goes well... but as soon as I want to put the data inside a sufficiently allowed array, the line reading stops at i=12286...
这是代码
int dim = nbvox[0]*nbvox[1]*nbvox[2];
float* hu_geometry = new float(dim);
int* hu_temp = new int(dim);
string line;
int i = 0;
ifstream in(hu_geom_file.c_str());
if(in.is_open())
{
while(getline(in, line))
{
hu_temp[i] = stoi(line);
cout << "i= " << i << " line= " << line << " hu_temp= " << hu_temp[i] << endl;
i++;
}
cout << __LINE__ << " i=" << i << endl;
in.close();
cout << __LINE__ << endl;
}
else cout << "Unable to open " << hu_geom_file << endl;
这是在得到错误之前我得到的最后一个输出...这很奇怪,因为每当我在while内注释hu_temp行时,仅cout即可运行2097152.
Here's the last output I get before getting the error... which is very strange because whenever I comment the hu_temp line inside the while, the cout alone works up to 2097152.
i= 12276 line= 0 hu_temp= 0
i= 12277 line= 0 hu_temp= 0
i= 12278 line= 0 hu_temp= 0
i= 12279 line= 0 hu_temp= 0
i= 12280 line= 0 hu_temp= 0
i= 12281 line= 0 hu_temp= 0
i= 12282 line= 0 hu_temp= 0
i= 12283 line= 0 hu_temp= 0
i= 12284 line= 0 hu_temp= 0
i= 12285 line= 0 hu_temp= 0
115 i=12286
*** Error in `G4Sandbox': free(): invalid pointer: 0x0000000001ba4c40 ***
Aborted (core dumped)
推荐答案
float* hu_geometry = new float(dim);
int* hu_temp = new int(dim);
是包含值 dim
的1个字符的数组.在某些时候,您遇到MMU边界并随机崩溃.
those are 1-char arrays containing the value dim
. At some point you're hitting a MMU boundary and crashes randomly.
您要写:
float* hu_geometry = new float[dim];
int* hu_temp = new int[dim];
,或者对于预先分配了 dim
个元素
or maybe better with vectors, pre-allocated with dim
elements
#include <vector>
std::vector<float> hu_geometry(dim);
std::vector<int> hu_temp(dim);
或在开始时未分配:
std::vector<int> hu_temp;
并在您的代码中:
hu_temp.push_back(stoi(line));
( hu_temp.size()
给出了大小和许多很好的功能,这些功能可以更好地描述此处)
(hu_temp.size()
gives the size and a lot of very nice features better described here)
这篇关于在C ++中读取大的.txt文件时出现奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!