Home > Backend Development > C++ > `delete ptr` vs. `delete[] ptr`: Why is One Safe and the Other a Memory Leak?

`delete ptr` vs. `delete[] ptr`: Why is One Safe and the Other a Memory Leak?

DDD
Release: 2025-01-03 08:15:40
Original
123 people have browsed it

`delete ptr` vs. `delete[] ptr`: Why is One Safe and the Other a Memory Leak?

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];
Copy after login

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:

  • delete ptr: Only frees the memory pointed to by ptr (the first element).
  • delete []ptr: Calls operator delete[] which correctly deallocates the entire array.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template