Home > Backend Development > C++ > How Does `delete[]` Know the Size of the Array It\'s Deleting?

How Does `delete[]` Know the Size of the Array It\'s Deleting?

Barbara Streisand
Release: 2024-11-17 09:07:03
Original
816 people have browsed it

How Does `delete[]` Know the Size of the Array It's Deleting?

Delete[] and Array Detection

In C , delete[] is used to delete arrays allocated using new[]. However, how does the system know that a pointer points to an array?

Compiler and Operating System

While the original question suggests that the language or compiler is unaware of the pointer's type, the reality is more nuanced. The compiler does not know whether a pointer is an array or a single-element pointer. However, the operating system (OS) can keep track of the type of allocation made with new.

Memory Management

When an array is allocated using new[], memory is allocated not only for the array elements but also for metadata that includes the array size. This metadata is stored in a header before the array elements. When delete[] is used, the OS checks this header to determine the array size.

Single Element vs. Array

In the case where a single element is allocated using new (like int* num = new int(1);), no metadata is added. Therefore, when deleteForMe(num); is called, the OS deletes only a single int.

The above is the detailed content of How Does `delete[]` Know the Size of the Array It's Deleting?. 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