V727. Return value of 'wcslen' function is not multiplied by 'sizeof(wchar_t)'.
The analyzer has detected an expression which it believes to be used for calculating the size (in bytes) of a buffer intended for storing a string. This expression is written with an error.
When solving the task of calculating the size of a char string, the standard solution is to use the "strlen(str) + 1" construct. The strlen() function calculates the length of some string, while 1 is used to reserve one byte for the null character. But when dealing with strings of the types wchar_t, char16_t, or char32_t, always remember to multiply the "strlen(str) + 1" expression by the size of one character, i.e. 'sizeof(T)'.
Let's examine a few synthetic error samples.
Example No. 1:
wchar_t *str = L"Test"; size_t size = wcslen(str) + 1 * sizeof(wchar_t);
Because of the missing parentheses, 'sizeof' is multiplied by 1 first and then the resulting value is added to 'strln(str)' function. The correct code should look as follows:
size_t size = (wcslen(str) + 1) * sizeof(wchar_t);
Example No. 2:
The expression may be written in a different order, when it is the function result which is multiplied by 'sizeof' first and then the resulting value is added to 1.
.... = malloc(sizeof(wchar_t) * wcslen(str) + 1);
It may also happen that you remember in the middle of writing the code that you should multiply the string length by "sizeof(wchar_t)" but add 1 out of habit. It will result in allocating 1 byte less memory than required.
The correct versions of the code look as follows:
.... = malloc(wcslen(str) * sizeof(wchar_t) + 1 * sizeof(wchar_t)); .... = malloc((wcslen(str) + 1) * sizeof(wchar_t));
This diagnostic is classified as: