Mar 21, 2014

[C] printf (and the like.) : warning: format not a string literal and no format arguments

printf format issue


// Case 1. This string can be verified at compile time and the compiler will allow it without warning:
printf("This string has no format");

// Case 2: For this case, the compiler can detect that you have a format specifier 
// and will raise a different warning. On my machine it said "warning: too few arguments for format".
printf("Not a safe string to %s"); 


// Case 3. Now this is somewhat your case. You are taking a string generated at runtime
// and trying to print it. The warning you are getting is the compiler warning you that
// there could be a format specifier in the string. Say for eg "bad%sdata".
// In this case, the runtime will try to access a non-existent argument to match the %s.
// Even worse, this could be a user trying to exploit your program
// (causing it to read data that is not safe to read).
char str[200];
scanf("%s", str)
printf(str)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.