Format String Vulnerability and Prevention with Example in C

Format String − It is an ASCII string that is used for formatting strings. It is an ASCII string consisting of texts and formatting parameters.

For formatting, the program’s output, there are various format strings in C.


These are bugs that arise due to errors in programming that might be made easily by the programmer. If any such error-prone code blog is passed to output functions like printf, sprintf, etc. Then the write operation is performed to an arbitrary memory address.



int main(){

   char buffer[100];
   strncpy(buffer, "Hii ", 5);

   return 0;


There are some measures that can be taken to prevent format string Vulnerabilities

  • Try to use format string as part of the program instead to input data. These can be easily solved using “%s” string format.

  • Use constant for creating format String and extract all variable strings as arguments of the function call instead of using them in constant string.

  • For cases where constant and variable string initialization norms cannot be followed format guards are used.