简体   繁体   中英

Having a SegFault where there should be none

Program keeps throwing a seg fault under conditions where it should not. I have arrays and vectors, and have tried both options. Seems to always throw the seg fault on the third value of the array/vector of 3. There is another functions after this that when commented out lets it go a few more times. But the results is the same, it still seg faults.

    char bits[3];//vector<char> bits(3,'0');
    vector<string> inputs;
    string temp;
    for(int x = 0;!i.eof();x++)
    {
            getline(i, temp);
            inputs.push_back(temp);
    }
    for(int x = 0; x < inputs.size();x++)
    {
       cout << endl << inputs[x];
    }
    for(int x = 0; x < 3;x++)
    {
       cout << endl << bits[x];
    }
    for(int cursor = 0;cursor< inputs.size();cursor++)
    {
    cout << endl << "bitstogoin " << cursor;
    cout << endl << inputs.size();
            bits[0]=inputs[cursor][0];
    cout << endl << "got1 " << bits[0];
            bits[1]=inputs[cursor][1];
    cout << endl << "got2 " << bits[1];
            bits[2]=inputs[cursor][2];  //seg faults on this line.
    cout << endl << "bitsin";
    for(int t = 0; t < 3;t++)
    {
    cout << bits[t];
   }

The commands that are being given via the input file look like: 100 10110101 101 11001011 111 110 000 111 110 etc...

Note: this probably has nothing to do with your segfault but should still be addressed.

The following input loop has two problems. First, the x is pointless because you never do anything with the value of x . Second, looping on eof() is rarely correct (see: Testing stream.good() or !stream.eof() reads last line twice ).

for(int x = 0;!i.eof();x++)
{
    getline(i, temp);
    inputs.push_back(temp);
}

Try the following instead:

while (getline(i, temp))
{
    inputs.push_back(temp);
}

In your code here:

 vector<string> inputs;
    string temp;
    for(int x = 0;!i.eof();x++)
    {
            getline(i, temp);
            inputs.push_back(temp);
    }

You read in strings and place them into a vector.

Ask yourself this? What is the length of each of these strings?

When you call

bits[2]=inputs[cursor][2];

You are accessing the 3rd character of a string in that vector. Before this statement try this:

if (inputs[cursor].size() < 3)
   cout << "String is less than 3!" << endl;

If your program prints that debug line, then you know you're in trouble.

Indeed, you're not really doing anything to check the lengths of your strings before you try to access characters in them.

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