RajSanpui
RajSanpui

Reputation: 12064

Why is this simple program giving a segmentation fault?

I have written a simple C++ program. The idea is, once it sees a non-alphabetic character, then till the time it see a new word (a blank) or the string ends, it keeps on incrementing the iterator.

This generates Segmentation fault, no idea why :( Please help.

#include <iostream>
using namespace std;

int main()
{
 string str("Hello yuio");
 string::iterator it=str.begin();

 while(it!=str.end())
 {
  cout << *it << endl;

  if(isalpha(*it)==0){
   cout << *it << ":Is not an alphabet\n";

   while((*it!=' ')||(it!=str.end()))
   {
     cout << *it << endl;
     it++;
   }
  }

if(it!=str.end()){it++;}
  } // while loop ends
}  // End of main

Upvotes: 1

Views: 673

Answers (3)

atzz
atzz

Reputation: 18010

while((*it!=' ')||(it!=str.end()))

The line above contains two errors.

  1. The condition says that the loop shall go on while the current character is not a space OR end of string is not reached yet. I.e., even when the end is reached but current char is not a space, the loop will proceed.

  2. Once you fixed this error (by replacing || with &&), you still try to dereference the end iterator (because the check for space comes before the check for end of string), which is not allowed. You have to switch the order of conditions:

    while((it!=str.end()) && (*it!=' '))

Upvotes: 5

Benoit Thiery
Benoit Thiery

Reputation: 6387

The problem is here:

while((*it!=' ')||(it!=str.end()))

When you reach the end of the string, the first part of the condition is true and so you continue looping and incrementing the iterator. You need to replace with &&:

while((*it!=' ')&&(it!=str.end()))

Upvotes: 2

Assaf Levy
Assaf Levy

Reputation: 1302

while((*it!=' ')||(it!=str.end()))

*it is evaluated before checking if it itself is ok to use. Change to:

while((it!=str.end())&&(*it!=' '))

Upvotes: 11

Related Questions