Hamza Khan Hamza Khan - 1 month ago 6
C++ Question

Deallocating memory while deleting an array in C++

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;
}

Answer

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.

Comments