5.83 <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.

Related concepts
5.64 New library features of C99
5.78 Additional <math.h> library functions in C99
5.79 Complex numbers in C99
5.80 Boolean type and <stdbool.h> in C99
5.81 Extended integer types and functions in <inttypes.h> and <stdint.h> in C99
5.82 <fenv.h> floating-point environment access in C99
5.84 <tgmath.h> type-generic math macros in C99
5.85 <wchar.h> wide character I/O functions in C99
Non-ConfidentialPDF file icon PDF versionARM DUI0472J
Copyright © 2010-2013 ARM. All rights reserved.