Why printf (char []) generates a warning, while printf ("asdf") does not

Possible duplicate:
warning: format is not a string literal and format arguments

I have a very simple question: why, when I do char[] s = "hi"; printf(s), it gives a warning: "warning: format is not a string literal and format arguments", meanwhile printf("aa")not.

I already read the difference between a char array and a string literal (one is const char const*, and the other is char*), but from printf()signature:

http://www.gnu.org/software/libc/manual/html_node/Formatted-Output-Functions.html#Formatted-Output-Functions

I see that it is suitable for any of these types. So my question is, why printf("aaa")not give any warnings (does it somehow verify that the literal is a constant, while the array is not)?

+5
source share
4 answers

Currently, the GNU compiler and many other compilers do check format strings for the printf-family against the given arguments. The compiler warns that it cannot do this for non-literal strings.

Using a non-literal format string is considered bad practice. Using a format string that you do not control is much worse.

+6
source

, 10-15 , , , printf (s), "s" . , . , puts(). , , printf, "%", printf ( "% s", s);

+4

, , , , :

/* "aa" is not dangerous, so do not display a warning */
printf("aa")

, :

/* the compiler doesn't know the content of the memory region pointed by `s`, so
   he can't determine if it dangerous or not. Then display a warning */
printf(s)
+1

: , , .

prinrf , ( , , ). , , - - , . ( ) , , (.. ).

, -, , , , , puts, printf. (IMHO, puts - C. - ", ", ?)

+1

All Articles