Udostępnij za pośrednictwem


C6209

warning C6209: using 'sizeof<variable1>' as parameter <number> in call to <function> where <variable2> may be an array of wide characters, did you intend to use character count rather than byte count?

This warning indicates that a parameter to a function call might incorrectly be a byte count instead of a character count. If this is the case, this defect is likely to cause a memory corruption or program crash, although some cases might cause an exploitable security hole.

A common cause of this defect is using sizeof on a character array. The sizeof operator always computes the number of bytes. For ANSI characters this is the same as the number of characters; however, for Unicode characters it is twice the number of characters.

It is usually safe to compute the number of elements in an array by dividing the size of the array by the size of each element.

This warning is generated when:

  • A variable is passed as one parameter and sizeof that variable is passed as another parameter.

  • Both the variable type and the formal parameter type are some variety of pointer-to-wide char.

Example

The following sample code generates this warning because sizeofpC is passed to my_wcsncpy function:

#include<windows.h>
extern void my_wcsncpy(wchar_t *, wchar_t *, size_t);

void f( )
{
  WCHAR pC[15];
  wchar_t* input = L"Hello, World!";
  
  my_wcsncpy(pC, input, sizeof pC);
  // code ...
}

To correct this warning, pass the correct size as shown in the following code:

#include<windows.h>
extern void my_wcsncpy(wchar_t *, wchar_t *, size_t);

void f( )
{
  WCHAR pC[15];
  wchar_t* input = L"Hello, World!";
  
  my_wcsncpy(pC, input, (sizeof pC) / (sizeof pC[0]));
  // code ...
}

It should be noted that the heuristic used can be incorrect for certain coding styles; therefore, this warning might not correspond to an actual defect in the code.

See Also

Reference

sizeof Operator

The sizeof Operator