CWE-135

Incorrect Calculation of Multi-Byte String Length. [String-Errors, Incorrect-Calculation]

Required inputs: IR

The product does not correctly calculate the length of strings that can contain wide or multi-byte characters.
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: 53
Excerpts 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