5.79 <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, "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 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 written to buffer. The buffer can never be overrun, provided its size is always greater than the size specified by size.

Note:

The C standard does not define what should happen if buffer + size exceeds 4GB (the limit of the 32-bit address space). In this scenario, the ARM implementation of snprintf does 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.
Non-ConfidentialPDF file icon PDF versionARM DUI0472M
Copyright © 2010-2016 ARM Limited or its affiliates. All rights reserved.