Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does delete[] know the array length in C++? [duplicate]

Tags:

c++

arrays

Imagine I have a pointer to an array of integers and then I want to delete it like I do below:

int * numbers = new int[10];
delete[] numbers;

How does the delete operator knows where the array numbers ends to free that memory (since C++ does not keep track of the length of the array as far as I know)?

Thanks!

like image 915
Daniel Oliveira Avatar asked Jan 28 '26 13:01

Daniel Oliveira


1 Answers

It can do it however it wants. There are two common ways:

  1. The implementation may use an associative array of allocated pointers mapped to their sizes.

  2. The implementation may allocate a few extra bytes at the beginning to store the size and pass a pointer into the block to the caller.

like image 95
David Schwartz Avatar answered Jan 30 '26 04:01

David Schwartz