Home >Backend Development >C++ >How Does `delete[]` Know How Many Elements to Delete from an Array?

How Does `delete[]` Know How Many Elements to Delete from an Array?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 19:46:11708browse

How Does `delete[]` Know How Many Elements to Delete from an Array?

How does delete[] Decipher an Array

The code in question:

void deleteForMe(int* pointer)
{
     delete[] pointer;
}

has undefined behavior if the pointer is not pointing to an array, as it blindly performs a delete[] operation. However, when the pointer references an array, as in:

int main()
{
     int* arr = new int[5];
     deleteForMe(arr);
     return 0;
}

the OS somehow knows to only delete the specified array elements and not proceed beyond them.

The key to this behavior lies in C 's historical roots as a C-compatible language. To avoid burdening programmers who do not use arrays with unnecessary overhead, the delete[] syntax was introduced.

When a non-array allocation is made, such as:

Foo* foo = new Foo;

no extra overhead is incurred for array support. However, for array allocations, this overhead does exist. To indicate that the runtime libraries should use this information, the programmer must specify delete[] for array pointers.

Thus, the choice between delete and delete[] is based on the specific allocation being deleted. This allows for finer-grained memory management and aligns with C 's philosophy of minimalism.

The above is the detailed content of How Does `delete[]` Know How Many Elements to Delete from an Array?. For more information, please follow other related articles on the PHP Chinese website!

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