Is Operator Delete Equivalent to Operator Delete[]?
The behavior of deleting a dynamic array using either delete ptr or delete[] ptr in C has been a subject of confusion. Let's delve into the nuances and potential consequences to understand the proper usage.
When you allocate an array dynamically using new IP_ADAPTER_INFO[100], a contiguous block of memory is allocated, and a pointer ptr is returned pointing to the first element.
Using delete ptr:
- This is incorrect for an array.
- It attempts to delete a single object, releasing the memory allocated for the first element only.
- The remaining elements in the array are still allocated and remain in memory.
- This can lead to memory leaks and potential issues if accessed later.
Using delete[] ptr:
- This is the correct way to delete a dynamic array.
- It invokes the operator delete[] function, which is responsible for releasing the entire block of memory allocated for the array.
- All the elements in the array are deallocated, freeing up all the allocated memory.
Disassembly Code:
The provided disassembly code illustrates the difference between delete ptr and delete[] ptr.
- For delete ptr, only the first element's value is pushed onto the stack, and operator delete is called.
- For delete[] ptr, the array's address is pushed onto the stack, and operator delete[] is called, which deallocates the entire block of memory.
Undefined Behavior:
The question raises concerns about the consequences of using delete ptr for an array. The answer emphasizes that the result is undefined behavior.
- It could lead to unexpected crashes or memory corruption.
- The consequences can vary depending on the compiler, system configuration, and even seemingly unrelated factors.
- Relying on undefined behavior is strongly discouraged in any codebase.
The above is the detailed content of Is `delete ptr` Equivalent to `delete[] ptr` for Dynamic Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!