Versions Compared

Key

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

...

Because wchar_t and char are distinct types, many compilers will produce a warning if the 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 strncpy() in an attempt to copy up to 10 wide characters. However, because wide characters can contain null bytes, the copy operation may end earlier then than anticipated.

Code Block
bgColor#ffcccc
langc
#include <stddef.h>
#include <string.h>
 
void func(void) {
  wchar_t wide_str1[]  = L"0123456789";
  wchar_t wide_str2[] =  L"0000000000";

  strncpy(wide_str2, wide_str1, 10);
}

Noncompliant Code Example(Narrow

...

Strings with Wide String Functions)

This noncompliant code example incorrectly invokes the wcsncpy() function to copy up to 10 wide characters from narrow_str1 to narrow_str2. Because narrow_str2 is a narrow string, it has insufficient memory to store the result of the copy and the copy will result in a buffer overflow.

...