﻿# 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](https://pvs-studio.com/en/blog/terms/0088/)\. 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:

```cpp
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:

```cpp
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\.

```cpp
.... = 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:

```cpp
.... = malloc(wcslen(str) * sizeof(wchar_t) + 1 * sizeof(wchar_t));

.... = malloc((wcslen(str) + 1) * sizeof(wchar_t));
```