Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since delete [] knows array sizes, why is this information not available?

When I allocate a dynamic array in C++ (T * p = new T[n]), I use delete [] p to free the allocated memory. Obviously, the system knows the array size (in order among other things to call n times T's destructor). This is discussed elsewhere. For instance How does delete[] “know” the size of the operand array?. This is implemenation details.

But why was it not decided to make this information available?

Thx

like image 747
asbxl Avatar asked Jan 10 '18 14:01

asbxl


People also ask

How does delete know the size of the array?

When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.

What happens when delete an array?

Deleting array elements When the delete operator removes an array element, that element is no longer in the array.

What does delete [] do in C++?

But in C++, delete[] is an operator with a very specific behavior: An expression with the delete[] operator, first calls the appropriate destructors for each element in the array (if these are of a class type), and then calls an array deallocation function.

How does delete know the size of memory to be deleted?

Usually operator new allocates a memory block with some invisible for the user header that contains the size of the allocated block. free the memory, the de-allocator knows exactly how much memory to free. The delete operator just randomly selects memory cells for erasure.


2 Answers

delete[] might not necessarily know the exact array size. It might over-allocate for example, or do something else entirely bizarre yet conformant with the standard.

Facetiously the answer could also be on the lines that nobody has managed to convince the standards committee of the merits of the idea; perhaps sizeof[](p) could be the proposed syntax? sizeof is already a keyword, already has a runtime-evaluable flavour in C so it's not an enormous leap to envisage an equivalent in C++, and my [] distinguishes from sizeof(pointer type).

like image 76
Bathsheba Avatar answered Oct 06 '22 20:10

Bathsheba


It would inhibit optimisations where knowledge of array size is not nessesary:

int* foo = new int[...];
. . .
delete[] foo;

As int is a trivial type and does not have a destructor, compiler do not need to know how many ints are there. Even if it is an array of 1 int in 4 MB memory chunk.

const MyType* const foo = new MyType[. . .];
. . .
delete[] foo;

Here compiler knows size of the array, pointed by foo, and it knows, that it cannot change legally. So it just can use that information directly, and do not store amount of items in allocated array.

like image 44
Revolver_Ocelot Avatar answered Oct 06 '22 18:10

Revolver_Ocelot