Consider the following code:
void main()
{
int i = 0;
char j[22] = "This is a long string", k[3];
scanf("%2s", k);
sprintf(j, k);
for (; i < 21; printf("%c", j[i++]));
}
It is given that the output is:
U%ae'$ffq` ong string
What could be the input?
So I think it should be something like %d
or %x
. So it executes: sprintf(j, "%x");
but there's no corresponding variable to this format.
%x
or something else?It cannot be told for sure, but it looks evident that the input for k
is essentially some form of a format specifier. It can be any of the many.
After that, due to the missing argument to that format specifier, sprintf()
is invoking undefined behaviour, as stated in C11
, chapter §7.21.6.1
[..] If there are insufficient arguments for the format, the behavior is undefined. [...]
To avoid this kind of error, do not pass a user input as the format string to the printf()
family. Use a safer from, like
printf("fixed format string with format specifiers %s %d and all", arg1, arg2);