几个小时以来,我一直在尝试修复此段错误。此代码始终在第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;
}

最佳答案

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


最好不要在程序中四处散布魔术数字,使用常量或宏。

08-28 05:24