Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The delete[] operator deallocates a block of memory previously allocated for an array of objects via the new[] operator. It ensures proper object lifecycle management by invoking the destructor for each element in the array before returning the raw memory to the free store (heap).
delete[] pointer;

Mechanics of Execution

When delete[] is evaluated, the C++ runtime performs two distinct operations sequentially:
  1. Destruction: The runtime iterates through the array and invokes the destructor (~T()) for every initialized object. The destructors are strictly called in the reverse order of their construction (from the highest index down to index 0).
  2. Deallocation: After all destructors have completed, the runtime invokes the deallocation function—either the global operator delete[](void*) or a class-specific overload—to release the contiguous memory block back to the system.

Array Size Tracking (The “Cookie” Idiom)

Because delete[] only receives a pointer to the first element, the runtime must determine the number of elements to destroy. Compilers typically resolve this by allocating extra memory (often called an “array cookie” or metadata block) immediately preceding the memory address returned by new[]. When delete[] is invoked, the runtime reads this hidden metadata to determine the exact number of destructors to execute.

Technical Constraints and Undefined Behavior (UB)

  • Mismatched Operators: Using the scalar delete operator on a pointer allocated with new[], or using delete[] on a pointer allocated with scalar new, results in undefined behavior. This typically causes heap corruption or segmentation faults because scalar delete does not look for the array cookie and will fail to invoke the destructors for elements beyond the first.
  • Null Pointers: Applying delete[] to a nullptr is a guaranteed no-operation. The runtime performs a null check before attempting destruction or deallocation.
  • Double Free: Invoking delete[] more than once on the same memory address results in undefined behavior, usually triggering a heap corruption exception or program crash.
  • Polymorphic Arrays: Invoking delete[] on an array of derived-class objects via a base-class pointer results in undefined behavior. Pointer arithmetic relies on the static type’s sizeof, meaning the runtime will calculate incorrect memory offsets for the destructors if the base class and derived class differ in size.
Master C++ with Deep Grasping Methodology!Learn More