Main Content

Misuse of narrow or wide character string

Narrow (wide) character string passed to wide (narrow) string function

Description

This defect occurs when you pass a narrow character string to a wide string function, or a wide character string to a narrow string function.

Misuse of narrow or wide character string raises no defect on operating systems where narrow and wide character strings have the same size.

Risk

Using a narrow character string with a wide string function, or vice versa, can result in unexpected or undefined behavior.

If you pass a wide character string to a narrow string function, you can encounter these issues:

  • Data truncation. If the string contains null bytes, a copy operation using strncpy() can terminate early.

  • Incorrect string length. strlen() returns the number of characters of a string up to the first null byte. A wide string can have additional characters after its first null byte.

If you pass a narrow character string to a wide string function, you can encounter this issue:

  • Buffer overflow. In a copy operation using wcsncpy(), the destination string might have insufficient memory to store the result of the copy.

Fix

Use the narrow string functions with narrow character strings. Use the wide string functions with wide character strings.

Examples

expand all

#include <string.h>
#include <wchar.h>

void func(void)
{
    wchar_t wide_str1[]  = L"0123456789";
    wchar_t wide_str2[] =  L"0000000000";
    strncpy(wide_str2, wide_str1, 10);
}

In this example, strncpy() copies 10 wide characters from wide_strt1 to wide_str2. If wide_str1 contains null bytes, the copy operation can end prematurely and truncate the wide character string.

Correction — Use wcsncpy() to Copy Wide Character Strings

One possible correction is to use wcsncpy() to copy wide_str1 to wide_str2.

#include <string.h>
#include <wchar.h>

void func(void)
{
    wchar_t wide_str1[]  = L"0123456789";
    wchar_t wide_str2[] =  L"0000000000";
    wcsncpy(wide_str2, wide_str1, 10);
}

Result Information

Group: Programming
Language: C | C++
Default: Off
Command-Line Syntax: NARROW_WIDE_STR_MISUSE
Impact: High

Version History

Introduced in R2018b