3

I have the compiler error:

libvncserver/main.c:245: error: format not a string literal and no format arguments

And line 245 is:

fprintf(stderr,buf);

where buf is "char buf[256];"

I don't see what is wrong with line 245 and how can I fix it? When I comment out that line, the program compiles.

michael
  • 106,540
  • 116
  • 246
  • 346

2 Answers2

6

What is wrong is that any printf function expects a const char * while you are providing just a char *. Since the buffer can contain whatever you want the compiler is not sure that it will contain a correct format string. Just do

fprintf(stderr,"%s",buf);

so that it will be sure that you are not going to pass something strange.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 6
    Supplying a `char *` argument for a `const char *` parameter is not wrong; in fact, it is quite common and normal. A `const char *` parameter means that the function promises not to modify the argument string; it does not demand that the caller provide a constant argument. (The rest of the answer is more or less correct, though I'd consider icktoofay's answer more accurate.) – ibid Feb 17 '12 at 06:34
  • When you work on a CPU with Harvard architecture, the compiler will usually store literals strings in the instruction memory. Writable buffers will be located in the data memory. In this case, if you declare a parameter as const char *, the compiler will generate instructions to read the data from the instruction memory (i.e. FLASH). So, in general no, if a function expect a literal you cannot pass a writable buffer. Unfortunately the term 'const char *' is also used to say 'I will not modify your buffer'... and that's the source of confusion here. – fabrizi0 Mar 03 '14 at 22:39
4

If buf contains a format specifier like %s, the program will try to read an argument that you haven't provided, which might crash your program or corrupt your stack. GCC is warning you about that. Change it to this:

fprintf(stderr, "%s", buf);
icktoofay
  • 126,289
  • 21
  • 250
  • 231