Format String Vulnerabilities (printf/etc.)

When passing a non-literal-constant string as the first parameter to “printf()”/sprintf()” and friends, one runs the risk of format string vulnerabilities (more information in the link). As a result, it is important to always use a literal constant string to format the string. E.g:

# Bad code


fgets(str,sizeof(str), stdin);
str[sizeof(str)-1] = '\0';
printf(str);

should be replaced with:

fgets(str,sizeof(str), stdin);
str[sizeof(str)-1] = '\0';
printf("%s", str);

One can also use the relevant warning flags of GCC and compatible compilers to warn and possibly generate an error for that.