开发者

Segmentation fault in small text processing program

I have a c++ function read_inputdata to read some inputfile and write the values to a an array. I first declare an array of appropriate length, and with the function I fill it with the values in the inputfile.

But I get a segmentation fault. Anybody an idea what I did wrong?

#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);

When I compile and run this I get:

Declaring the arrays
Calling function read_inputdata
Segmentation fault

So at the moment he calls the function read_inputdata something goes wrong, because he doesn't reach std::cout << "In function read_inputdata" << std::endl;.

The function:

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 = NUL开发者_运维技巧L;
            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;
}


Probably running out of stack. Please use pointers, dynamic allocations and even better, 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);


My guess would be that j is exceeding the permissible range of 0..1. Try this:

        #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++;
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜