|Non-Confidential||PDF version||ARM DUI0472M|
|Home > Compiler Coding Practices > <stdio.h> snprintf family of functions in C99|
sprintf family of functions found in the C90 standard header
<stdio.h> can be dangerous.
In the statement:
sprintf(buffer, "Error %d: Cannot open file '%s'", errno, filename);
the full output of the formatting operation is written into
buffer regardless of whether there is enough space to hold it.
Consequently, more characters can be output than might fit in the memory allocated to the
snprintf functions found in the C99
<stdio.h> are safe versions of the
sprintf functions that prevent buffer overrun. In the
snprintf(buffer, size, "Error %d: Cannot open file '%s'", errno, filename);
size specifies the maximum
number of characters that can be written to
buffer can never be overrun, provided its size is always greater than the size specified by
buffer + sizeexceeds 4GB (the limit of the 32-bit address space). In this scenario, the ARM implementation of
snprintfdoes not write any data to the buffer (to prevent wrapping the buffer around the address space) and returns the number of bytes that would have been written.