Code where a value returned by the sizeof() operator is multiplied by another sizeof() operator most always signals an error. It is unreasonable to multiply the size of one object by the size of another object. Such errors usually occur when working with strings.
Let's study a real code sample:
TCHAR szTemp; DWORD dwLen = ::LoadString(hInstDll, dwID, szTemp, sizeof(szTemp) * sizeof(TCHAR));
The LoadString function takes the buffer's size in characters as the last argument. In the Unicode version of the application, we will tell the function that the buffer's size is larger than it is actually. This may cause a buffer overflow. Note that if we fix the code in the following way, it will not become correct at all:
TCHAR szTemp; DWORD dwLen = ::LoadString(hInstDll, dwID, szTemp, sizeof(szTemp));
Here is a quotation from MSDN on this topic:
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, 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) would give the proper size of the buffer.
This is the correct code:
TCHAR szTemp; DWORD dwLen = ::LoadString(hInstDll, dwID, szTemp, sizeof(szTemp) / sizeof(TCHAR));
Here is another correct code:
const size_t BUF_LEN = 256; TCHAR szTemp[BUF_LEN]; DWORD dwLen = ::LoadString(hInstDll, dwID, szTemp, BUF_LEN);
According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-131.
You can look at examples of errors detected by the V531 diagnostic.