Passing narrow strings string arguments to wide string functions or wide strings string arguments to narrow string functions can lead to unexpected and undefined behavior. 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 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 diagnostic if the an inappropriate function is used (see MSC00-C. Compile cleanly at high warning levels).
...
This noncompliant code example incorrectly uses the strncpy() 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 string.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#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);
} |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#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;
} |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
| [ISO/IEC 9899:2011] | 7.24.2.4, "The strncpy Function"7.29.4.2.2, "The wcsncpy Function" |
...