Passing narrow strings arguments to wide string functions or wide strings arguments to narrow character string functions can lead to unexpected behavior and undefined behavior. Scaling Scaling problems are likely (see ARR39-C. Do not add or subtract a scaled integer to a pointer) because of the difference in size between wide and narrow characters. Because wide Because wide strings are terminated by a null wide character and can contain null bytes, determining the length is also problematic.
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).
...
This noncompliant code example incorrectly invokes the wcsncpy() function to copy up to 10 wide characters from a narrow_str1 to a to narrow_str2. Because 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.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <wchar_t.h>
void func(void) {
char narrow_str1[] = "01234567890123456789";
char narrow_str2[] = "0000000000";
wcsncpy(narrow_str2, narrow_str1, 10);
} |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
void func(void) {
wchar_t wide_str1[] = L"0123456789";
wchar_t *wide_str2 = (wchar_t *)malloc(strlen(wide_str1) + 1);
if (wide_str2 == NULL) {
/* Handle error */
}
/* ... */
free(wide_str2);
wide_str2 = NULL;
} |
The strlen() function determines the number of characters that precede the terminating null character. However, wide characters can contain null bytes, particularly when converted from when expressing characters from the ASCII character set, as in this example. As a result, the strlen() function will return the number of bytes preceding the first null byte in the wide string.
...