简体   繁体   中英

stack smashing detected while reading file

I have made a method to read data from a input.txt file here is the code

void readData()
{
    ifstream myfile;
    myfile.open("input.txt");
    char v[1], w[1];
    while (myfile.good())
    {
        string line;
        getline(myfile, line, ' ');
        strcpy(v, line.c_str());
        getline(myfile, line);
        strcpy(w, line.c_str());
        //graph->addEdge(v[0], w[0]);
    }
    myfile.close();
}

I am trying to get two vertices from input file whose one line contains two character. and I have made a addEdge method in my Graph class which takes two char as input to add it into graph.

here is my input.txt file

A B
A C
F D
D C
U I
U D
B I
F B

but when I run the programme it is giving error

*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

I do not understand why this error is comming. I have read other questions on stackoverflow for this error. But none of them are getting error while reading a file.

one more thing I want to add, if I remove the line strcpy(w, line.c_str());then the code is working, maybe this line is causing the error. I am not sure about that. please help me out in this error. Thanks in advance..

The immediate problem is that a single-character C-style string occupies two bytes: the character and the NUL terminator. So your arrays are too short and you're writing outside their bounds.

However, you don't need arrays at all. You can just store the appropriate character:

void readData()
{
    ifstream myfile;
    myfile.open("input.txt");
    while (myfile.good())
    {
        string line;
        getline(myfile, line, ' ');
        char v = line[0];
        getline(myfile, line);
        char w = line[0];
        graph->addEdge(v, w);
    }
}

Also note that there's no need to explicitly close the file. Its destructor will do it for you just fine.


Note that the code above does not do any error checking. In production code, you should always test the result of input operations (such as the getline call) for success. The simplest solution could look like this:

void readData()
{
    ifstream myfile;
    myfile.open("input.txt");
    while (myfile.good())
    {
        string line;
        if (!getline(myfile, line, ' ') || line.empty())
            break;
        char v = line[0];
        if (!getline(myfile, line) || line.empty())
            break;
        char w = line[0];
        graph->addEdge(v, w);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM