Delete[] and Array Detection
In C , delete[] is used to delete arrays allocated using new[]. However, how does the system know that a pointer points to an array?
Compiler and Operating System
While the original question suggests that the language or compiler is unaware of the pointer's type, the reality is more nuanced. The compiler does not know whether a pointer is an array or a single-element pointer. However, the operating system (OS) can keep track of the type of allocation made with new.
Memory Management
When an array is allocated using new[], memory is allocated not only for the array elements but also for metadata that includes the array size. This metadata is stored in a header before the array elements. When delete[] is used, the OS checks this header to determine the array size.
Single Element vs. Array
In the case where a single element is allocated using new (like int* num = new int(1);), no metadata is added. Therefore, when deleteForMe(num); is called, the OS deletes only a single int.
The above is the detailed content of How Does `delete[]` Know the Size of the Array It's Deleting?. For more information, please follow other related articles on the PHP Chinese website!