Well I don't think that it's really important but since the program has to store the length because of delete[] anyway, Why can't we get this "stored information" ?
There are two ways by which we can create an expression and calculate the length of an array in C. Using the sizeof() operator and using pointer arithmetic. The sizeof() operator in C calculates the size of passed variables or datatype in bytes.
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
To find the length of the array we have to use sizeof() function. The sizeof() function in C calculates the size in bytes of the passed variable or data type. To calculate the length of array in C, first, calculate the total size of the array and then calculate the size of the data type.
Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.
The implementation only needs to store the length, and typically only does, if the type is not trivially destructible (i.e., it needs to generate calls to a destructor) and the array was created with the new[] operator.
Since that property of the arrayed type bears no relation to the size of the array, it is more elegant simply to call the length "cookie" a private implementation detail.
To get the length of a complete array object (not a mere pointer), you can use std::extent< decltype( arr ) >::value
or std::end( arr ) - std::begin( arr )
.
Using new[]
with a class with a destructor is a code smell. Consider std::vector
instead. The overhead vs raw new[]
(considering all bytes that need to be allocated, wherever they are) is one pointer's worth of bytes, and the benefits are innumerable.
Consider the case:
char* a = new char[100];
Now a
needs to point to a buffer that's at least 100 chars big, but the system might have allocated a bigger buffer to fulfill this.
With this in mind, we can see that the system is free to immediately forget the size the program asked for, as long as it can still deallocate the buffer properly later. (Either by remembering the size of the allocated buffer or doing the memory allocation with some smart data structure where only the pointer to the start is required)
So, in the general case, the information you are looking for is not, in fact, stored anywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With