【问题标题】:Weird error when reading a large .txt file in c++ [duplicate]在 C++ 中读取大型 .txt 文件时出现奇怪的错误 [重复]
【发布时间】:2017-03-18 14:07:20
【问题描述】:

我正在尝试读取一个非常大的 .txt 文件,该文件具有 128x128x128=2097152 行(线性化 3d 空间),其中仅包含一个 0 或 1 行(不要问为什么)...我将我的代码修剪为几行,似乎当我计算线和增量时,一切都很顺利......但是一旦我想将数据放入足够允许的数组中,行读取停止在 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。

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)

【问题讨论】:

    标签: c++


    【解决方案1】:
    float* hu_geometry = new float(dim);
    int* hu_temp = new int(dim);
    

    这些是包含值 dim 的 1 字符数组。在某些时候,您会遇到 MMU 边界并随机崩溃。

    你想写:

    float* hu_geometry = new float[dim];
    int* hu_temp = new int[dim];
    

    或者使用矢量可能更好,预先分配dim 元素

    #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() 给出了尺寸和许多非常好的功能,更好地描述了here

    【讨论】:

    • 我现在觉得自己很愚蠢,哈哈……但是非常感谢……这是由 3 个人审核的,并且在将其发布到堆栈之前工作了很多时间……我想我们需要一些从我们的代码空间...
    • 这个问题一直在发生。需要好眼力才能捕捉到。根本不使用数组,而是使用向量来明确修复它。
    • 是的,但我发现它们稍后在我的代码中更难处理,因为这都与 CUDA 混合在一起......我通常会使用向量,但在将它们发送到 GPU 之前我必须使用它们
    • @Feynstein:不是;只需将 &amp;myVector[0] 发送到 GPU,或多或少就像您现在所做的那样。
    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多