来自std :: getline的带有分隔符的Segfault

时间:2016-11-24 02:13:07

标签: c++ csv segmentation-fault

几个小时,我一直试图解决这个段错误。此代码始终在第500次迭代后发送SIGSEGV。 Here's the TEST.csv I've been using。一旦while循环命中第二组AMU值,getline会立即崩溃程序。我已经梳理了这个,找不到拯救生命的问题。

值得注意的是:我无法在每台机器上重现此错误!绝对有些记忆在某个地方被破坏了,但我无法解决这个问题!

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <climits>
using namespace std;
int main(int argc, char **argv)
{
    ifstream data;
    data.open("TEST.csv", ifstream::in);
    float amudata[505];
    //initialize amudata
    for (int x = 0; x < 505; x++) amudata[x] = INT_MIN;
    std::string line;
    //toss out the first 137 lines of config data
    for (int x = 0; x < 137; x++)
    {
        std::getline(data, line);
    }
    //debug iteration counter
    int x = 0;
    //toss out the first part of the timestamp
    //this is where SEGV happens
    while (std::getline(data, line, ' '))
    {
        x++;
        //toss out second part of timestamp
        getline(data, line, ',');
        //read and store the index, which is amu times 10
        std::getline(data, line, ',');
        int index = std::atof(line.c_str()) * 10;
        //read and store the amu intensity
        std::getline(data, line, ',');
        float intensity = std::atof(line.c_str());
        //some debug output
        cout << index << " " << intensity << " ";
        cout << line << " " << x << endl;
        //keep track of only the maximum intensities
        if (amudata[index] < intensity) 
        {
            amudata[index] = intensity;
        }
    }
    for (int x = 0; x < 505; x++)
    {
        printf("%f\n", amudata[x]);
    }
    data.close();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您的amudata数组太小了。

处理完这一行后,您的程序崩溃了:

2016/11/23 16:49:06.146,   50.500, -3.6263e-010,

当你这样做时:

int index = std::atof(line.c_str()) * 10;

line"50.500",因此设置index = 505。然后你做:

amudata[index] = intensity;

amudata的允许索引是从0504,所以你要在数组边界外写字,这会导致未定义的行为。

你需要:

float amudata[506];
//initialize amudata
for (int x = 0; x < 506; x++) amudata[x] = INT_MIN;

最好不要在程序中传播这样的魔法数字,使用常量或宏。