1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Segmentation fault reading string on cin read

  1. Apr 15, 2012 #1
    1. The problem statement, all variables and given/known data
    I'm trying to read a string from cin. When it hits the "cin >> strWord" statement, I get the following error message: Segementation fault (core dumped). The input file is named "data4nine". I'm really not sure what a segmentation fault is and why I'm getting it


    3. The attempt at a solution
    Code (Text):
        while (!cin.eof())
        {
            cin >> strWord;
            intWords++;
            cntVowsCons(strWord, intVowels, intConsonants);
            strFormatted = FormatWord(strWord);
            lenWords += strWord.length();
            lenFormatted += strFormatted.length();


            if(strFormatted.length() % 2 != 0)
                SwapMidChar(strFormatted);
            if(istenth(intWords, tenth))
                cout << strFormatted << endl;
            else
                cout << strFormatted;
           
        }
     
  2. jcsd
  3. Apr 15, 2012 #2
    Here are my files
     

    Attached Files:

  4. Apr 15, 2012 #3
    Segmentation fault is generally a memory access violation. In this case, your program will attempt to access part of a string that doesn't exist (I know where this is in your code, but it should be left as an exercise to you). You may attempt to find it by scrutinizing your code or by using a debugger.
     
  5. Apr 15, 2012 #4

    I like Serena

    User Avatar
    Homework Helper

    Hi OSalcido! :smile:

    When an access violation (aka segmentation violation) occurs in a program, it may or may not crash with a core dump.
    And if it does crash, it's often not a the point where the access violation occurred.

    In any program an access violation always occurs in one of 2 forms.

    Either you follow a pointer that does not point anywhere.
    Since you're not using pointers, that won't be a problem.

    Or you are indexing an array outside of its bounds.
    Each of your for-loops should be defined such that you can always be sure your string is indexed inside its bounds.
    Can you check if that is the case?
     
  6. Apr 15, 2012 #5
    Yes! Thank you guys I did check the loops and fixed the issues. Thanks a bunch
     
  7. Apr 16, 2012 #6

    I like Serena

    User Avatar
    Homework Helper

    Your welcome. ;)

    Btw, if you use an input of just one word and a newline, or none at all, you may get some results you don't expect.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Segmentation fault reading string on cin read
  1. Reading memory (Replies: 5)

  2. Reading a File (Replies: 2)

Loading...