Is delete[] Equivalent to delete?
Consider the C code below:
IP_ADAPTER_INFO *ptr = new IP_ADAPTER_INFO[100];
When attempting to free the allocated memory, one might consider using delete ptr;. However, it's crucial to understand the implications of such an action:
Potential Memory Leak:
Using delete ptr; to free an array allocated with new[] can result in undefined behavior and potential memory leaks. The reason lies in how C manages memory for arrays:
In our example, ptr points to an array of 100 IP_ADAPTER_INFO objects, not a single object. Attempting to delete a single object instead of the entire array can corrupt memory and cause undefined behavior.
Disassembled Code Comparison:
The disassembly code generated by Visual Studio 2005 highlights the difference between delete ptr; and delete []ptr;:
Undefined Behavior:
Using delete ptr; for an array can lead to undefined behavior and is strongly discouraged. It's essential to consistently use new[] for allocation and delete [] for deallocation of arrays to avoid memory leaks and ensure proper memory management.
The above is the detailed content of Is `delete ptr;` Equivalent to `delete[] ptr;` for Array Deallocation in C ?. For more information, please follow other related articles on the PHP Chinese website!