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;
}
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;
}
Last updated