Is Deleting an Array with delete Equivalent to delete[]?
When dealing with dynamic arrays, it's crucial to understand the difference between deleting individual elements with delete and deleting the entire array with delete[].
Why delete ptr Can Cause Undefined Behavior
In the provided code:
IP_ADAPTER_INFO *ptr = new IP_ADAPTER_INFO[100];
ptr points to an array of 100 IP_ADAPTER_INFO structures. Deleting the pointer with delete ptr is equivalent to deleteing the first element of the array. However, this leaves the remaining 99 elements allocated. This can lead to a memory leak.
Disassembly Code Analysis
The disassembly code generated by Visual Studio 2005 for delete ptr and delete []ptr clearly demonstrates the difference:
Conclusion
To avoid undefined behavior and prevent memory leaks, always use delete []ptr to deallocate arrays dynamically allocated with new. Despite some compilers might handle delete ptr gracefully, it's an unreliable practice and should be avoided.
The above is the detailed content of `delete ptr` vs. `delete[] ptr`: Why is One Safe and the Other a Memory Leak?. For more information, please follow other related articles on the PHP Chinese website!