If C++ doesn't "remember" the size of arrays (we use the address of the start of the array), then why is there a difference between "delete" and "delete []"?
For example, wouldn't using "delete" on the address of a dynamic array of size 1 be interpreted the same as using "delete" on an address stored in a pointer? Essentially, as I see it, the same operation is happening: memory is freed at that address, and C++ doesn't "know" whether or not that is the start of an array or not, just that it is a place in memory.
Posted Apr 24, 2021, 1:27 AM UTC
The implementation of new[]/delete[] knows how big the buffer is and how many destructors to call.
But that information is not exposed to the program.
I'm not sure what a buffer is. Do you mean that it knows the size of the array?
Yes
Then why is that information not accessible? Thank you for taking the time to provide these answers, by the way.
Because the creators of C and C++ decided you didn't need to know.
There are implementation specific ways
https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapsize
https://man7.org/linux/man-pages/man3/malloc_usable_size.3.html
The standard C++ way is to use a
std:: vector, which remembers the size for you.