Segmentation fault reading string on cin read

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 6K views
OSalcido
Messages
66
Reaction score
0

Homework Statement


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


The Attempt at a Solution


Code:
	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;
		
	}
 
Physics news on Phys.org
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.
 
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?
 
Yes! Thank you guys I did check the loops and fixed the issues. Thanks a bunch