How to fix this compiler error 'format not a string literal and no format arguments'

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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.

回答1:

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.



回答2:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!