do not use printf without %s to print a string

This tip submitted by pavan kumar on 2010-11-22 11:25:14. It has been viewed 49989 times.
Rating of 6.2 with 247 votes



Since the printf() function takes strings as arguments, you might think that you do not need the format specifier "%s" while printing a string.

Example:

int main()
{
  char string[30]="Hello c programers";
  printf(string);
  return 0;

}


However, this can be very dangerous--what if your string includes a format specifier like %s or %d? Because printf is a varargs function, it uses the format string to decide how many arguments it takes. If you provide one argument, but put in the format specifier, it will assume it has more arguments than it does, and read them off the stack. This will cause it to print out data from stack memory for those format strings. This can reveal information about the state of your program's memory to an attacker who adds format specifiers to the string--or just cause bugs. Don't do it!



More tips

Help your fellow programmers! Add a tip!