When running this code with the input shown in the top multi-line comment, I get a segmentation fault runtime error. Can anyone please explain why or how I can fix this?
Removed code section to avoid self plagiarism
When running this code with the input shown in the top multi-line comment, I get a segmentation fault runtime error. Can anyone please explain why or how I can fix this?
Removed code section to avoid self plagiarism
There are multiple errors in your code.
First, I assume you enter the input strings in a Tab-delimited manner, as you use %[^\t]
as format string in scanf
. If you enter no Tab, it will read indefinitely, and will overflow your input array soon.
Second, the constant EOF
is not the terminator for a C-style string. A string is always terminated with a null character (or a zero - they're essentially the same). EOF is a negative value and thus will not appear in a string normally. So your for
loop that finds the length of the string will run indefinitely and out of bounds.
Third, your length
is actually one more than the length of the string because the excessive length++
after the for
loop. When the loop exits, userString[length]
is already pointing to the zero terminator (assumt you've corrected the error in the above paragraph). There's no need to increment it.
Finally, it is not necessary to test the character at length
because it's zero. You would like to change i <= length
into i < length
, although if you don't, the program will work fine for your example.