>
>
>
V542. Suspicious type cast: 'Type1' to …


V542. Suspicious type cast: 'Type1' to ' Type2'. Consider inspecting the expression.

The analyzer found a very suspicious explicit type conversion. This type conversion may signal an error. You should review the corresponding code fragment.

For example:

typedef unsigned char Byte;

void Process(wchar_t ch);
void Process(wchar_t *str);

void Foo(Byte *buf, size_t nCount)
{
  for (size_t i = 0; i < nCount; ++i)
  {
    Process((wchar_t *)buf[i]);
  }
}

There is the Process function that can handle both separate characters and strings. There is also the 'Foo' function which receives a buffer-pointer at the input. This buffer is handled as an array of characters of the wchar_t type. But the code contains an error, so the analyzer warns you that the 'char' type is explicitly cast to the ' wchar_t *' type. The reason is that the "(wchar_t *)buf[i]" expression is equivalent to "(wchar_t *)(buf[i])". A value of the 'char' type is first fetched out of the array and then cast to a pointer. This is the correct code:

Process(((wchar_t *)buf)[i]);

However, strange type conversions are not always errors. Consider a sample of safe code taken from a real application:

wchar_t *destStr = new wchar_t[len+1];
...
for (int j = 0 ; j < nbChar ; j++)
{
  if (Case == UPPERCASE)
    destStr[j] =
      (wchar_t)::CharUpperW((LPWSTR)destStr[j]);
  ...

Here you may see an explicit conversion of the 'wchar_t' type to 'LPWSTR' and vice versa. The point is that Windows API and the CharUpperW function can handle an input value both as a pointer and a character. This is the function's prototype:

LPTSTR WINAPI CharUpperW(__inout  LPWSTR lpsz);

If the high-order part of the pointer is 0, the input value is considered a character. Otherwise, the function processes the string.

The analyzer knows about the CharUpperW function's behavior and considers this code safe. But it may produce a false alarm in some other similar situation.

This diagnostic is classified as:

You can look at examples of errors detected by the V542 diagnostic.