Tip of the week#8:Do not use printf without %s to print a string

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

int main()
  char string[30]="Hello c programers";
  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!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

FREE C Cheatsheet - Speed Up Your C Programming.

FREE C Cheatsheet - Speed Up Your C Programming.

Download a 7-page free cheat sheet for easy and quick access to C Concepts, Snippets, and Syntax.

Thank you! Check you inbox and access your cheat-sheet