Edit

Share via


Warning C6278

'variable' is allocated with array new [], but deleted with scalar delete. Destructors will not be called.

Remarks

This warning appears only in C++ code and indicates that the calling function has inconsistently allocated memory with the array new [] operator, but freed it with the scalar delete operator. This usage is undefined behavior according to the C++ standard and the Microsoft C++ implementation.

There are at least three reasons that this mismatch is likely to cause problems:

  • The constructors for the individual objects in the array are invoked, but the destructors aren't invoked.

  • If global, or class-specific, operator new and operator delete aren't compatible with operator new[] and operator delete[], unexpected results are likely to occur.

  • It's always risky to rely on undefined behavior.

The exact ramifications of this defect are difficult to predict. It might result in leaks for classes with destructors that perform memory de-allocation. It could cause inconsistent behavior for classes with destructors that perform some semantically significant operation, or memory corruptions and crashes when operators have been overridden. In other cases the mismatch might be unimportant, depending on the implementation of the compiler and its libraries. Analysis tools can't always distinguish between these situations.

If memory is allocated with array new [], it should be freed with array delete[].

Code analysis name: ARRAY_NEW_DELETE_MISMATCH

Example

The following sample code generates warning C6278:

class A
{
  // members
};

void f( )
{
  A *pA = new A[5];
  // code ...
  delete pA;
}

To correct this warning, use the following sample code:

void f( )
{
  A *pA = new A[5];
  // code ...
  delete[] pA;
}

If the underlying object in the array is a primitive type such as int, float, enum, or pointer, there are no destructors to call. In these cases, warning C6283 is reported instead.

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.