Warning C6384

Dividing sizeof a pointer by another value

This warning indicates that a size calculation might be incorrect. To calculate the number of elements in an array, you sometimes divide the size of the array by the size of the first element. However, when the array is actually a pointer, the result is typically different than intended.

Remarks

If the pointer is a function parameter and the size of the buffer wasn't passed, it isn't possible to calculate the maximum buffer available. When the pointer is allocated locally, the size used in the allocation should be used.

Code analysis name: DIVIDING_SIZEOF_POINTER

Example

The following code generates warning C6384:

#include <windows.h>
#include <TCHAR.h>

#define SIZE 15

void f( )
{
  LPTSTR dest = new TCHAR[SIZE];
  char src [SIZE] = "Hello, World!!";
  if (dest)
  {
    _tcsncpy(dest, src, sizeof dest  / sizeof dest[0]);
  }
}

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

#include <windows.h>
#include <TCHAR.h>

#define SIZE 15

void f( )
{
  LPTSTR dest = new TCHAR[SIZE];
  char src [SIZE] = "Hello, World!!";
  if (dest)
  {
    _tcsncpy(dest, src, SIZE);
  }
}

To correct this warning using the safe string function _tcsncpy_s, use the following code:

void f( )
{
  LPTSTR dest = new TCHAR[SIZE];
  char src [SIZE] = "Hello, World!!";
  if (dest)
  {
    _tcsncpy_s(dest, SIZE, src, SIZE);
  }
}

The use of new and delete has many pitfalls in terms of memory leaks and exceptions. To avoid these kinds of potential leaks altogether, use the mechanisms that are provided by the C++ Standard Library (STL). These include shared_ptr, unique_ptr, and containers such as vector. For more information, see Smart pointers and C++ Standard Library.

See also

_mbsnbcpy_s, _mbsnbcpy_s_l
sizeof Operator