CWE-135¶
Incorrect Calculation of Multi-Byte String Length. [String-Errors, Incorrect-Calculation]
Required inputs: IR
Demonstrative Examples
Example 1
The following example would be exploitable if any of the commented incorrect malloc calls were used.
Example Language:C
#include <stdio.h>
#include <strings.h>
#include <wchar.h>
int main() {
wchar_t wideString[] = L"The spazzy orange tiger jumped " \
"over the tawny jaguar.";
wchar_t *newString;
printf("Strlen() output: %d\nWcslen() output: %d\n",
strlen(wideString), wcslen(wideString));
/* Wrong because the number of chars in a string isn't related to its length in bytes //
newString = (wchar_t *) malloc(strlen(wideString));
*/
/* Wrong because wide characters aren't 1 byte long! //
newString = (wchar_t *) malloc(wcslen(wideString));
*/
/* Wrong because wcslen does not include the terminating null */
newString = (wchar_t *) malloc(wcslen(wideString) * sizeof(wchar_t));
/* correct! */
newString = (wchar_t *) malloc((wcslen(wideString) + 1) * sizeof(wchar_t));
/* ... */
}
The output from the printf() statement would be:
(result)
Strlen() output: 0
Wcslen() output: 53Excerpts from CWE [https://cwe.mitre.org], Copyright (C) 2006-2026, the MITRE Corporation. See section 9.4. "3rd-Party Licenses" in the documentation for full details.Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
no_sizeof |
Not using “sizeof” in length calculation |
None |
False |
not_accounting_for_terminator |
“wcslen” does not include the terminating null |
None |
False |
not_wchart_argument_to_sizeof |
“sizeof” should be used with “wchar_t” as an argument |
None |
False |
using_strlen_for_wide_string |
Using “strlen” instead of “wcslen” |
None |
False |
Options
This rule shares the following common options: exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.