...
| Code Block | ||||
|---|---|---|---|---|
| ||||
wchar_t wide_str1[] = L"0123456789"; wchar_t wide_str2[] = L"0000000000"; wcsncpy(wide_str2, wide_str1, 10); /* Use of proper-width function */ char narrow_str1[] = "0123456789"; char narrow_str2[] = "0000000000"; strncpy(narrow_str2, narrow_str1, 10); /* Use of proper-width function */ |
Noncompliant Code Example (strlen())
In this noncompliant code example, the strlen() function is used to determine the size of a wide character string:
| Code Block | ||||
|---|---|---|---|---|
| ||||
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 counts the number of characters in a null-terminated byte string preceding the terminating null byte. However, wide characters contain null bytes, particularly when taken 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 string.
Compliant Solution
This compliant solution correctly calculates the number of bytes required to contain a copy of the wide string (including the termination character):
| Code Block | ||||
|---|---|---|---|---|
| ||||
wchar_t wide_str1[] = L"0123456789";
wchar_t *wide_str2 = (wchar_t *)malloc(
(wcslen(wide_str1) + 1) * sizeof(wchar_t)
);
if (wide_str2 == NULL) {
/* Handle error */
}
/* ... */
free(wide_str2);
wide_str2 = NULL;
|
Risk Assessment
Failure to use the proper-width string functions can lead to buffer overflows and the execution of arbitrary code by an attacker.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...