Is the Syntax delete ptr Equivalent to delete[] ptr?
The differences between delete and delete[] may seem subtle, but they are crucial for memory management in C .
Consider the following code snippet:
IP_ADAPTER_INFO *ptr = new IP_ADAPTER_INFO[100];
This code allocates an array of 100 IP_ADAPTER_INFO structures using new. To deallocate this memory, we need to use the appropriate deletion syntax.
Using delete ptr:
delete ptr;
This syntax is incorrect. ptr points to an array of objects, so it must be deleted using delete[]. Failing to do so leads to undefined behavior, which can result in memory leaks or other unpredictable consequences.
Using delete[] ptr:
delete[] ptr;
This syntax is correct. delete[] is used to deallocate arrays. It will invoke the appropriate destructor for each element in the array and free the memory allocated for the entire array.
Disassembly Code Analysis:
The provided disassembly code demonstrates the difference between delete ptr and delete[] ptr.
For delete ptr, a single call to operator delete is made, indicating that it is attempting to delete a single object.
For delete[] ptr, a call to operator delete[] is made, indicating that it is attempting to delete an array of objects.
Conclusion:
To avoid memory leaks and undefined behavior, it is crucial to use the correct deletion syntax for arrays. delete ptr should be used for deleting single objects, while delete[] ptr should be used for deleting arrays.
The above is the detailed content of When Should I Use `delete ptr` vs. `delete[] ptr` in C ?. For more information, please follow other related articles on the PHP Chinese website!