Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wide characters can frequently contain null bytes if taken from the ASCII character set. As a result, using narrow - character functions that rely on null-byte termination can lead to obtuse behavior. Likewise, a narrow - character string that is properly null-terminated might not be considered so in a wide - character function. Improper use of narrow and wide character strings could result in buffer overflows.

...

This example uses strncpy, which copies, at most, 10 bytes but will stop copying after it encounters a null - byte. Because wide characters can contain null - bytes, the code can stop copying prematurely. It is important to recognize that many narrow - string functions are byte functions and so can terminate prematurely.

...

Note that wcsncpy does not perform null - termination if the source string contains more wide characters than the destination. As a result, it is possible for an attacker to exploit such a vulnerability by passing a maliciously crafted string to wcsncpy. If the code is intended to copy a certain number of bytes, it can overflow the buffer by writing multiple bytes because wcsncpy measures copying by wide characters, not by bytes.

...

Implementation Details

The C standard recognizes Standard recognizes wchar_t[] and char[] as distinct types. As a result, many compilers will yield a warning if the inappropriate function is used. For example, the following warnings were generated when the second noncompliant example was compiled with no flags in GCC on a Linux i686 platform:

...

Similar warnings were issued by the compiler for the first noncompliant example , with respect to the arguments of the strncpy function instead.

...

This compliant solution uses the appropriate-width function versions. Using wcsncpy for wide - character strings and strncpy for narrow - character strings ensures that data is not truncated or overwriting extra memory.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

ISO/IEC 9899:2011 Section 7.24.2.4, "The strncpy function," and Section 7.29.4.2.2, "The wcsncpy function"

...

...