0

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.

  1. What does the function do in this case? It seems like an address
  2. What could be the input? Is it %x or something else?
Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234
RonErikson
  • 91
  • 8
  • `void main()` --> `int main(void)` – Sourav Ghosh Aug 17 '15 at 11:47
  • 3
    @SouravGhosh Your comment is not necessarily correct, [see this](http://stackoverflow.com/a/31263079/584518). – Lundin Aug 17 '15 at 11:51
  • If your `scanf()` scans in any `sprintf()`-conversion-specifiers, the behavior is undefined, as the `sprintf()` will not have the corresponding arguments. – EOF Aug 17 '15 at 11:51
  • @Lundin technically, yes, but for vast majority of the cases, it will be applicable (normal, hosted env). For freestanding env, there's no restriction, at all. :) – Sourav Ghosh Aug 17 '15 at 12:02

2 Answers2

1

sprintf(j, k); should be sprintf(j, "%s", k); - please check sprintf prototype.

artm
  • 16,141
  • 4
  • 27
  • 46
1

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);
Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234