| |||
| Home > Compiler Coding Practices > <stdio.h> snprintf family of functions in C99 | |||
Using the sprintf family of functions found
in the C90 standard header <stdio.h> can be dangerous.
In the statement:
sprintf(buffer, size, "Error %d: Cannot open file '%s'", errno, filename);
the variable size specifies the minimum
number of characters to be inserted into buffer. Consequently,
more characters can be output than might fit in the memory allocated
to the string.
The snprintf functions found in the C99
version of <stdio.h> are safe versions of
the sprintf functions that prevent buffer overrun.
In the statement:
snprintf(buffer, size, "Error %d: Cannot open file '%s'", errno, filename);
the variable size specifies the maximum
number of characters that can be inserted into buffer. The
buffer can never be overrun, provided its size is always greater
than the size specified by size.