Is it true that a pointer assigned to the starting address of a dynamically allocated array does not have the information of the size of the array? So we have to use another variable to store its size for later processing the array through the pointer.
But when we free the dynamically allocated array, we don’t specify the size, instead we just “free ptr” or “delete [] ptr”. How could free or delete know the size of the array? Can we use the same scheme to avoid storing the size of the array in another variable?
Thanks!
Yes, this is true.
deleteknows the size of the memory chunk becausenewadds extra information to the chunk (usually before the area returned to the user), containing its size, along with other information. Note that this is all very much implementation specific and shouldn’t be used by your code.So to answer your last question: No – we can’t use it – it’s an implementation detail that’s highly platform and compiler dependent.
For example, in the sample memory allocator demonstrated in K&R2, this is the “header” placed before each allocated chunk:
sizeis the size of the allocated block (that’s then used byfree, ordelete).