tgikf
tgikf

Reputation: 557

C++ SIGSEGV Segmentation fault in loop

I have the following code which ends up in a segmentation fault.

    for (int a=0; a<inputFileList.size(); a++)
    {
        fileLines = readFile(inputFileList[a].c_str());
        for (int i = 0; i < fileLines.size(); i++)
        {
            if (fileLines[i].find("text") != string::npos)
            {
                bool warnFound = false, errFound = false;
                i++;
                while (fileLines[i].find("message") == string::npos && i < fileLines.size())
                {
                    if (fileLines[i].find("error") != string::npos)
                        errFound = true;
                    else if (fileLines[i].find("warning") != string::npos)
                        warnFound = true;
                    i++;
                }
                i--;
                if (errFound)
                    errCtr++;
                else if (warnFound)
                    warnCtr++;
                else
                    okCtr++;
            }
        }
        fileLines.clear();
    }

When i remove the while-loop, i don't get this error anymore. But i don't know what's wrong with this loop.

Thx for your support

Upvotes: 1

Views: 447

Answers (3)

Boaz Yaniv
Boaz Yaniv

Reputation: 6424

I'm not sure if it has anything to do with the error you're getting, but you seem to have a problem with the i++ on line 7. It may increase i even when i == fileLines.size() - 1, so fileLines[i].find("message") on the next line would access a non-existing item.

Upvotes: 0

user2100815
user2100815

Reputation:

This :

  while (fileLines[i].find("message") == string::npos && i < fileLines.size())

should be:

  while (i < fileLines.size() && fileLines[i].find("message") == string::npos )

Upvotes: 1

Gunther Piez
Gunther Piez

Reputation: 30419

The while should probably read

while (i < fileLines.size() && fileLines[i].find("message") == string::npos)

Upvotes: 6

Related Questions