sprintf function --output format string to string variable

The sprintf function is a function that can output a format string to a string variable. The printf function outputs to the standard output, but this output destination is char type. Think of the sprintf function as changing a string variable declared as a array in. The sprintf function can be used by loading stdio.h.

#include <stdio.h>
int sprintf(char * str, const char * format, ...);

The first argument is the output destination string. The second argument is the format string, which is the same as described in printf function. The third and subsequent arguments are variable-length arguments, which are the same as those explained in the printf function.

The sprintf function is a function that can cause a buffer overrun.

Sample sprintf function

This is a sample of the sprintf function.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  const char * name = "kimoto";
  int32_t age = 40;
  
  char message [255];
  
  sprintf(message, "I'm%s. Age is%d.", name, age);
  
  printf("%s\n", message);
}

This is the output result.

I'm kimoto. Age is 40.

This sample does not cause a buffer overrun.

sprintf function and Buffo overrun

I will write about the danger of the sprintf function and the buffo overrun.

For example, consider that user input changes the value to embed in the format. For example, suppose you haven't put a length limit on a user's name in a web input form. Also assume that the length of the output destination string is short.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  const char * name = "long_long_long_name";
  int32_t age = 40;
  
  char message [16];
  
  // Buffer overrun !!!
  sprintf(message, "I'm%s. Age is%d.", name, age);
  
  printf("%s\n", message);
}

When a buffer overrun occurs, data is written to an unintended memory area. I'm not familiar with what kind of problem this causes, so I'll leave it to the security engineer. As an engineer writing a program, keep in mind that you shouldn't have a buffo overrun.

There is also a snprintf function that can limit the maximum number of writes, so use it properly according to the purpose.

Associated Information