When array is created using 'new' and deleted using 'delete' operator, delete knows the size o开发者_高级运维f array. As mentioned in other SO threads, this size information is stored in metadata.
My question: what exactly is stored in metadata and how much space is needed for that? Is it only the size which is stored in metadata?
According to C++ Standard 5.3.4/12:
new T[5] results in a call of operator new[](sizeof(T)*5+x),
<...>where x is a non-negative unspecified values representing array allocation overhead. <...> The amount of overhead may vary from one invocation of new to another.
It is implementation-defined. I would say there is at least four bytes for the length, but there could also be "next" and "previous" pointers to adjacent blocks. There could also be a "magic" number that the runtime uses to make sure you haven't accidentally overwritten their section of the memory and so on.
But you shouldn't ever need to worry about that. In fact, for a small array like your int[10]
(which is 40 bytes) you might find that the largest amount of space is actually taking up by padding (for example, there could be 24 bytes of padding added to make the allocation a multiple of 32 - which could be done for performance reasons, say.
At the end of the day, though, as I said it's completely up to the implementation to decide how they do it.
This kind of question is very compiler and plataform specific. Each compiler implements this in a different manner. The standard says what should be implemented, not exactly how shoult it be implemented.
Of course, this metadata must contain the array size, or some other information that allow us to infer it. Otherwise, we wouldn't be capable of calling the destructor for all the objects in the array.
That's going to depend on your standard library. Even malloc() needs data to know how many bytes were allocated. For an example, look at the glibc malloc:
http://sourceware.org/git/?p=glibc.git;a=blob_plain;f=malloc/malloc.c;hb=HEAD
Minimum overhead per allocated chunk: 4 or 8 bytes
Each malloced chunk has a hidden word of overhead holding size and status information.
精彩评论