The C Standard, 126.96.36.199 [ISO/IEC
9899:2011], provides the following sample implementation of the
This function is supposed to output a character string of 26 characters at most, including the terminating null character. If we count the length indicated by the format directives, we arrive at 25. Taking into account the terminating null character, the array size of the string appears sufficient.
However, this implementation
assumes that the values of the
data are within normal ranges and does nothing to enforce the range
limit. If any of the values print more characters than expected, the
function may overflow the
array. For example, if
has the value
then 27 characters (including the terminating null character) are
printed, resulting in a buffer overflow.
The POSIX® Base Specifications
Std 1003.1:2013] says the following about the
These functions are included only for compatibility with older implementations. They have undefined behavior if the resulting string would be too long, so the use of these functions should be discouraged. On implementations that do not detect output string length overflow, it is possible to overflow the output buffers in such a way as to cause applications to fail, or possible system security violations. Also, these functions do not support localized date and time formats. To avoid these problems, applications should use
strftime()to generate strings from broken-down times.
The C Standard, Annex K, also defines
, which can be used as a secure substitute for
function appears in the list of obsolescent functions in MSC24-C.
Do not use deprecated or obsolescent functions.
Noncompliant Code Example
This noncompliant code example invokes the
function with potentially unsanitized data:
Compliant Solution (
function allows the programmer to specify a more rigorous format and
also to specify the maximum size of the resulting time string:
This call has the same effects as
but also ensures that no more than
characters are printed, preventing buffer overflow.
Compliant Solution (
The C Standard, Annex K, defines the
function, which serves as a close replacement for the
function but requires an additional argument that specifies the
maximum size of the resulting time string: