CWE-135: Incorrect Calculation of Multi-Byte String Length

Description

The product does not correctly calculate the length of strings that can contain wide or multi-byte characters.

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-06-29 00:00:00+00:00

Organization :

MITRE
Example Vulnerable Codes

Example - 1

The following example would be exploitable if any of the commented incorrect malloc calls were used.



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));/* ... */#include <stdio.h>#include <strings.h>#include <wchar.h>int main() {}

The output from the printf() statement would be:


Strlen() output: 0Wcslen() output: 53

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.