3

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!

Daniel Oliveira
  • 1,280
  • 14
  • 36

1 Answers1

2

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278