...
Note that this code does not prevent wrapping unless the unsigned long long type is at least 4 bits larger than size_t.
Noncompliant Code Example (size_t)
The mbstowcs() function converts a multibyte string to a wide character string, returning the number of characters converted. If an invalid multibyte character is encountered, mbstowcs() returns (size_t)(-1). Depending on how size_t is implemented, comparing the return value of mbstowcs() to signed integer literal -1 may not evaluate as expected.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h>
void func(wchar_t *pwcs, const char *restrict s, size_t n) {
size_t count_modified = mbstowcs(pwcs, s, n);
if (count_modified == -1) {
/* Handle error */
}
} |
Compliant Solution (size_t)
To ensure the comparison is properly performed, the return value of mbstowcs() should be compared against -1 cast to type size_t:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h>
void func(wchar_t *pwcs, const char *restrict s, size_t n) {
size_t count_modified = mbstowcs(pwcs, s, n);
if (count_modified == (size_t)-1) {
/* Handle error */
}
} |
Risk Assessment
Failure to cast integers before comparing or assigning them to a larger integer size can result in software vulnerabilities that can allow the execution of arbitrary code by an attacker with the permissions of the vulnerable process.
...