Udostępnij za pośrednictwem


C6278

warning C6278: <variable> is allocated with array new [], but deleted with scalar delete. Destructors will not be called

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 is undefined behavior according to the C++ standard and the Microsoft VC++ implementation. There are at least three reasons that this is likely to cause problems:

  • The constructors for the individual objects in the array are invoked, but the destructors are not invoked. 

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

  • It is always very 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; 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 tool cannot always distinguish between these situations.

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

Example

The following sample code generates this warning:

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 be called. In these cases warning C6283 is reported instead.