TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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).
Mechanics of Execution
Whendelete[] is evaluated, the C++ runtime performs two distinct operations sequentially:
- 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 index0). - 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)
Becausedelete[] 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
deleteoperator on a pointer allocated withnew[], or usingdelete[]on a pointer allocated with scalarnew, results in undefined behavior. This typically causes heap corruption or segmentation faults because scalardeletedoes not look for the array cookie and will fail to invoke the destructors for elements beyond the first. - Null Pointers: Applying
delete[]to anullptris 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’ssizeof, 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





