SEGFAULT与STD :: getline一起使用定界线

Segfault from std::getline with delimiter

本文关键字:定界线 一起 getline STD SEGFAULT      更新时间:2023-10-16

几个小时,我一直在尝试修复此segfault。该代码在第500次迭代之后总是发送Sigsegv。这是我一直在使用的test.csv。一次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("%fn", amudata[x]);
    }
    data.close();
    return 0;
}

您的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;

最好不要在程序中像魔术数字一样传播魔术数字,使用常数或宏。