I am new to C++ so sorry if this question is dumb.
I am solving this problem: http://codeforces.me/contest/707/problem/A
And couldn't understand why this solution failed: http://codeforces.me/contest/707/submission/20019326 According to http://www.cplusplus.com/reference/cstdio/scanf/ , the %s tag should only take one character at a time, right? So reading into a 1 element character array should be fine. Switching variable x to a 2 element character array makes this work for some reason.
Also, the particular test case that fails works locally for me?









s: Any number of non-whitespace characters, stopping at the first whitespace character found you need '%c' for reading one character.
Using
char x[1];and reading a single character leads to undefined behaviour because there is no space for the \0 character at the end. So, this null character(**\0**) is written outside the memory belonging to the array, which might cause segmentation fault or might silently use the memory, which could be the memory of some other variable in the code (which is what is happening in your case).I took your code and submitted with print statement to find whats going on. Look at the output
The input is
n = 2andm = 2but after the character is read, the value of n becomes 0. So, what might have happened is that the null character might have been overwritten in the memory belonging to the variable n. This is not the case always and that is why its an undefined behaviour. We can't be sure this will happen everywhere this code is run.That is why when you change the size of the array to more than 1, it will work since there will be memory separately available for the null character.
Wow thanks so much for the detailed answer! It makes sense now.
So in general, I should use a character array at least 1 larger than expected? (or maybe just instantiate it with a number way larger than necessary)
Yes, you are right. But, in general using scanf("%s") is considered dangerous since it does not have boundary checking as we have seen in this case. You could use fgets() but I am not sure if that is better than scanf or not since I generally just use cin or getline.
I agree this is UB, but this
char x[1];is allocated on stack and space allocated in multiples of 4 for 32-bit code so it seems there would be space for zero terminator anyway.On another note: I'm getting quite a few down votes for this post. Is there somewhere else I should be taking my C++ questions?