﻿# V531\. The sizeof\(\) operator is multiplied by sizeof\(\)\. Consider inspecting the expression\.

Код, в котором значение, возвращаемое оператором sizeof\(\), умножается на другой оператор sizeof\(\), практически всегда свидетельствует о наличии ошибки\. Бессмысленно умножать размер одного объекта на размер другого объекта\. Чаще всего подобные ошибки встречаются при работе со строками\.

Рассмотрим реальный пример кода:

```cpp
TCHAR szTemp[256];
DWORD dwLen =
  ::LoadString(hInstDll, dwID, szTemp,
               sizeof(szTemp) * sizeof(TCHAR));
```

Функция LoadString в качестве последнего аргумента принимает размер буфера в символах\. В Unicode версии приложения мы сообщим функции, что размер буфера больше, чем он есть на самом деле\. Это может привести к переполнению буфера\. Заметим, что следующее исправление вовсе не является корректным:

```cpp
TCHAR szTemp[256];
DWORD dwLen =
  ::LoadString(hInstDll, dwID, szTemp, sizeof(szTemp));
```

Приведем на эту темы выдержку из MSDN:

"Using this function incorrectly can compromise the security of your application\. Incorrect use includes specifying the wrong size in the nBufferMax parameter\. For example, if lpBuffer points to a buffer szBuffer which is declared as TCHAR szBuffer\[100\], then sizeof\(szBuffer\) gives the size of the buffer in bytes, which could lead to a buffer overflow for the Unicode version of the function\. Buffer overflow situations are the cause of many security problems in applications\. In this case, using sizeof\(szBuffer\)/sizeof\(TCHAR\) or sizeof\(szBuffer\)/sizeof\(szBuffer\[0\]\) would give the proper size of the buffer\."

Корректный вариант кода:

```cpp
TCHAR szTemp[256];
DWORD dwLen =
  ::LoadString(hInstDll, dwID, szTemp,
               sizeof(szTemp) / sizeof(TCHAR));
```

Другой корректный вариант:

```cpp
const size_t BUF_LEN = 256;
TCHAR szTemp[BUF_LEN];
DWORD dwLen =
  ::LoadString(hInstDll, dwID, szTemp, BUF_LEN);
```