4

In C++ when we assign an array there is no way to find out the size of the array once it has been initialized. Then how does the delete operator know the amount of memory to delete when I am trying to deallocate memory at the end of my program.

int main()
{
    int* p = new int[10];
    int* q = new int[30];
    //... bunch of code
    //...
    // ... bunch of code
    delete[] p;
    delete[] q;
    return 0;
}
3
  • This is all handled by your compiler and/or the C++ library. Sufficient to say that The Right Thing Will Happen. Commented Nov 2, 2016 at 23:09
  • 2
    The short answer is "however it wants to". Commented Nov 2, 2016 at 23:12
  • isocpp.org/wiki/faq/freestore-mgmt#num-elems-in-new-array Commented Nov 2, 2016 at 23:13

1 Answer 1

12

The new operator ends up creating an entry on the heap, and the heap allocator knows how to de-allocate things it's previously allocated. This information isn't normally available to your code because it's all C++ internals you're not supposed to mess with.

So basically the heap metadata describes this allocation.

Remember that in C++ you can write your own allocator, so new and delete[] might end up interfacing with that if you so desire. If you look at how std::allocator is defined, note that you're not obligated to tell anyone what allocations have been made, nor how big any particular allocation is. The allocator has a tremendous amount of freedom here, and the specification doesn't allow for a lot of interrogation.

Sign up to request clarification or add additional context in comments.

1 Comment

The deallocate function of allocator traits that allocator aware containers call actually does take a size along with a pointer, which is supposed to represent the size of the previous allocation. So to use an allocator generically you are obligated to track your own heap request sizes in some fashion and pass them back. So it's quite different from the situation with new and delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.