小文本处理程序中的分段错误

时间:2011-03-28 11:03:38

标签: c++ segmentation-fault

我有一个c ++函数read_inputdata来读取一些输入文件并将值写入一个数组。我首先声明一个适当长度的数组,并使用函数我用输入文件中的值填充它。

但是我遇到了分段错误。谁知道我做错了什么?

#define MAX 140160
void read_inputdata(double input[MAX], char files[40]);

char inputfiles1[40] = "input/Hesse04/FR_Hes_rad.txt";
std::cout << "Declaring the arrays" << std::endl;
double input1[MAX];
std::cout << "Calling function read_inputdata" << std::endl;
read_inputdata(input1, inputfiles1);

当我编译并运行它时,我得到:

Declaring the arrays
Calling function read_inputdata
Segmentation fault

所以目前他称函数read_inputdata出错了,因为他没有达到std::cout << "In function read_inputdata" << std::endl;

功能:

void read_inputdata(double input[MAX], char files[40])
{
    std::cout << "In function read_inputdata" << std::endl;
    std::ifstream inputfile;
    inputfile.open(files);
    if (inputfile.is_open())
    {
        char temp[100];
        double getal[2][MAX];
        int i = 0;
        while(!inputfile.getline(temp, 100).eof())
        {
            char delims[] = "\t ,";
            char *result = NULL;
            result = strtok( temp, delims );
            int j=0;
            while( result != NULL )
            {
                getal[j][i]=atof(result);
                result = strtok( NULL, delims );
                j++;
            }
            i++;
        }
        inputfile.close();
        for (int i = 0; i < MAX; i++)
        {
            input[i] = getal[1][i];
        }
    }
    else std::cout << "WARNING: unable to open file" << std::endl;
}

2 个答案:

答案 0 :(得分:6)

可能用完了堆栈。请使用指针,动态分配,甚至更好,std::vector

#define MAX 140160
void read_inputdata(double *input, char *files);

char inputfiles1[40] = "input/Hesse04/FR_Hes_rad.txt";
std::cout << "Declaring the arrays" << std::endl;
double *input1 = new double[MAX];
std::cout << "Calling function read_inputdata" << std::endl;
read_inputdata(input1, inputfiles1);

答案 1 :(得分:2)

我的猜测是j超过0..1的允许范围。试试这个:

        #include <assert.h>

        ...

        int j=0;
        while( result != NULL )
        {
            assert(j < 2); // make sure that we don't try to write beyond the bounds of getal !
            getal[j][i]=atof(result);
            result = strtok( NULL, delims );
            j++;
        }