How Memory Allocators Know the Array Size for Delete[]
In C , the delete[] operator is used to deallocate an array of objects from memory. However, unlike the new[] operator, which explicitly requires the array size, delete[] seemingly operates without this information. How does it determine the size of the array?
When you allocate memory on the heap using new[], the memory allocator allocates a contiguous block of memory for the array elements and stores additional information about the allocation, including its size. This information is typically stored in a header immediately preceding the allocated memory.
Standardization
The method of storing the array size with the allocated memory is not standardized in C itself. Different memory allocators implement various techniques:
Retrieval of Array Size
During deletion, delete[] retrieves the array size from the associated header or memory allocator. By knowing the size, delete[] can efficiently deallocate the entire array of objects.
Conclusion
In summary, the memory allocated by new[] carries information about its size, either through heap metadata, memory headers, or pointer values. This information is used by the delete[] operator to determine the array size during deallocation, enabling efficient memory management without the need to explicitly provide the size.
The above is the detailed content of How Does `delete[]` Know the Size of the Array It's Deallocating?. For more information, please follow other related articles on the PHP Chinese website!