I ran into this code:
char str; scanf("%s", &str);
Of course, this emits this warning:
a.c:6:17: warning: format specifies type 'char *' but the argument has type 'char (*)' [-Wformat] scanf("%s", &str); ~~ ^~~~~~~
I know that the correct way is to remove the
& and type
scanf("%s", str) instead. But it does work, so my question is if this could cause any problems. Is it UB? When I switched
str to a pointer instead of an array it (obviously) did not work. But can this cause any problem when using an array?
(I had a discussion about an answer here, where the answerer did not want to change his answer to the correct way)
Yes, the code is undefined behaviour. The argument corresponding to
%s must have the type
char *. This is described in C17 184.108.40.206/12 under the
[...] the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.
which says fairly clearly that the pointer should have pointer-to-character type, and not point to the whole array.
Undefined behaviour means that anything can happen. It might behave as if you omitted the
&, or it might format your hard drive.
Given that it is extremely easy to avoid undefined behaviour in this case, I don't really see any reason to engage in arguments about whether it is OK to rely on the behaviour of undefined behaviour in this situation.