sprintf

Prototype

int sprintf(char* str, const char* format, ...);

This function writes a formatted string to the array pointed to by str. The format argument is a string that specifies how the subsequent arguments are formatted. The ... indicates that the function can take a variable number of arguments.

Vulnerable example

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char buffer[8];
  sprintf(buffer, "%s", argv[1]);
  return 0;
}

In this code, the sprintf function is used to copy the contents of argv[1] (a command line argument) into the buffer array, which has a fixed size of 8 bytes. If the length of argv[1] is greater than 8 bytes, it will overwrite memory beyond the bounds of the buffer array, potentially causing a buffer overflow.

Prevent

To prevent this vulnerability, the program should ensure that the length of the data being written to the buffer is within the bounds of the buffer's size. For example, the following code uses snprintf (a variant of sprintf that includes a size parameter) to ensure that the data being written to the buffer does not exceed its size:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char buffer[8];
  snprintf(buffer, sizeof(buffer), "%s", argv[1]);
  return 0;
}

Using snprintf ensures that the data written to the buffer array does not exceed its size, and prevents a buffer overflow vulnerability.

Last updated