0

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
jamin1003
  • 1
  • 1
  • Do you know what `scanf("%[^\t]", ...` does? – iBug Jul 28 '18 at 10:06
  • 1
    `EOF` is *not* a character. It is a status. Which documentation to `scanf()` did you read? – alk Jul 28 '18 at 10:09
  • [c - What is the difference between NULL, '\0' and 0 - Stack Overflow](https://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0) – user202729 Jul 28 '18 at 10:10
  • "*length should now be equal to the total number of characters entered*" - Why? Did you confirm this? What does your debugger say? – melpomene Jul 28 '18 at 10:12

1 Answers1

4

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • Re: input, if you use `scanf` at all (which you shouldn't), you should always check its return value to see whether it was successful, and you should never use unrestricted input formats (`%s`, `%[`) without a size limit. – melpomene Jul 28 '18 at 10:19
  • On the contrary, if `char` is signed for the implementation in question, I believe you'll find that `userString[length] != EOF` will fail if `userString[length` is `\377`. – dgnuff Jul 28 '18 at 10:25
  • @dgnuff Given that OP has posted example inputs, `\377` (or `\xFF`) is not the case. – iBug Jul 28 '18 at 10:36