Why does gcc -Wall give warning about zero-length format string?

SirGuy picture SirGuy · Mar 29, 2012 · Viewed 14.2k times · Source

I searched around a little bit for information on this but didn't find anything satisfactory. Is there some special behavior to the function call

sprintf(someString, "");

that explains why this is warning (on gcc with -Wall)? I only managed to find that the C standard allows zero-length format strings.

I tried the following example

#include <stdio.h>

int main()
{
    char str[2] = {'a', 'a'};
    sprintf(str, "");
    printf("\'%c\'\'%c\'\n", str[0], str[1]);
    return 0;
}

which prints out

'''a'

which is exactly what I expected to see. So, why the warning?

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Mar 29, 2012

The fact that GCC issues a warning usually has nothing to do with whether the construct is legal C, but whether the GCC developers consider it either a likely indication that you meant something other than what you write, or just bad style. Here are some examples:

  • if (x = 0) — you almost surely meant if (x == 0).
  • printf(str) — you almost surely meant either fputs(str, stdout) or printf("%s", str); as written, the code is very dangerous.
  • if (foo == bar & MASK) — you almost surely meant if (foo == (bar & MASK)).

etc.

In your case, I think GCC is questioning why you're calling sprintf(String, "") to do the equivalent of String[0]=0; (the latter is much shorter, faster, and clearer).