Home > Backend Development > C++ > Is `delete ptr;` Equivalent to `delete[] ptr;` for Array Deallocation in C ?

Is `delete ptr;` Equivalent to `delete[] ptr;` for Array Deallocation in C ?

Mary-Kate Olsen
Release: 2025-01-03 01:07:39
Original
685 people have browsed it

Is `delete ptr;` Equivalent to `delete[] ptr;` for Array Deallocation in C  ?

Is delete[] Equivalent to delete?

Consider the C code below:

IP_ADAPTER_INFO *ptr = new IP_ADAPTER_INFO[100];
Copy after login

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:

  • new[] allocates a contiguous block of memory for an array of objects.
  • delete ptr; attempts to deallocate a single object pointed to by ptr.

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;:

  • delete ptr; calls operator delete, which is meant for single object deletion.
  • delete []ptr; calls operator delete[], which is specifically designed for array deletion.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template