CXX.MALLOC.WCHAR_LENGTH

Use (wsclen()+1*sizeof(wchar_t)) when allocating memory with malloc for wchar_t buffers

The length of character strings that contained wide and multi-byte characters should be correctly calculated.

A violation of this rule occurs when the output of a wide or multibyte string, string length function is used as the memory allocation size. This results in the number of characters in the string. However, it is likely that a character is not a single byte with a standard string. Therefore, using the size returned by the size sent to new or malloc and copying the string to the newly allocated memory causes a buffer overflow. Another common way to misuse these strings is to mix standard strings with wide or multibyte strings in a single string.

Mitigation and prevention

Use (wsclen()+1*sizeof(wchar_t) when allocating memory with malloc for wchar_t buffers.

Vulnerable code example

Copy
    wchar_t * pw_bad = (wchar_t*) malloc(wsclen(sourceString) * sizeof(wchar_t));
    wchar_t * pw_good = (wchar_t *) malloc((wsclen(sourceString) + 1) * sizeof(wchar_t));

The above assignemnt to pw_bad uses an incorrect calculation for the required buffer. It is missing the "+1".