Passing narrow string arguments to wide string functions or wide string arguments to narrow string functions can lead to unexpected and undefined behavior. Scaling problems are likely because of the difference in size between wide and narrow characters. (See ARR39-C. Do not add or subtract a scaled integer to a pointer.) Because wide strings are terminated by a null wide character and can contain null bytes, determining the length is also problematic.
are distinct types, many compilers will produce a warning diagnostic
if an inappropriate function is used. (See MSC00-C.
Compile cleanly at high warning levels.)
Noncompliant Code Example (Wide Strings with Narrow String Functions)
This noncompliant code example incorrectly uses the
function in an attempt to copy up to 10 wide characters. However,
because wide characters can contain null bytes, the copy operation may
end earlier than anticipated, resulting in the truncation of the wide
Noncompliant Code Example (Narrow Strings with Wide String Functions)
This noncompliant code example incorrectly invokes the
function to copy up to 10 wide characters from
is a narrow string, it has insufficient memory to store the result of
the copy and the copy will result in a buffer overflow.
This compliant solution uses the proper-width functions. Using
for wide character strings and
for narrow character strings ensures that data is not
truncated and buffer overflow does not occur.
Noncompliant Code Example (
In this noncompliant code example, the
function is used to determine the size of a wide character string:
function determines the number of characters that precede the
terminating null character. However, wide characters can contain
null bytes, particularly when expressing characters from the
ASCII character set, as in this example. As a result, the
function will return the number of bytes preceding the first null byte
in the wide string.
This compliant solution correctly calculates the number of bytes required to contain a copy of the wide string, including the terminating null wide character: