C ++ Dynamic Memory Size in Runtime Mode

This is something that I was interested in for some time, and could not find an answer for:

Why does this happen when you allocate something on the heap, you cannot determine the size of it only with the pointer, but you can delete it using only the pointer, and somehow C ++ knows how many bytes will be freed?

Is this related to how it is stored on the heap? Is this information there but not shown in C ++?

And maybe this should be a separate question, but I think it is very related, so I will ask him here:

Why exactly a dynamic array of elements should be deleted using delete [] , and not just a simple delete command; why does C ++ need this extra information to properly free all memory?

+6
source share
1 answer

When the allocation is performed, a small part of the memory immediately before [or, technically, somewhere else, but is just the most common scenario) will store the size of the allocation, and in the case of new [] also save the number of allocated objects.

Please note that the C ++ standard does not provide any way to get this information for any reason: it may not accurately describe what is allocated, for example, the size of the array may well be rounded to some “good” border [almost all modern allocators are rounded to 16 bytes, at least so that memory can be used for SSE and other similar SIMD implementations on other processor architectures]. Therefore, if you allocate 40 bytes, it will report 48, which is not what you asked for, so that would be pretty confusing. And, of course, there is no guarantee that the information is stored in ALL - this may be implied by other information that is stored in the "admin" block of the allocation.

And, of course, you can use the new location, in which case there is no administrator block, and the distribution will not be deleted in the usual way - some arbitrary code cannot be distinguished.

delete differs from delete [] in that delete [] will know how many objects have been allocated, and call the destructor for all these objects. It is also possible [or even likely] that new [] stores the number of elements in this way, which means that calling delete [] on something that was not created using new [] will be terribly wrong.

And as Zan Lynx noted, if there is no destructor for objects (for example, when you allocate data for int or struct { int x; double y; } , etc.), including classes that do not have a constructor [note that if you have another class inside the class, the compiler will create a destructor for you]), then there is no need to store a counter or do anything else, so the compiler MAY, if it wishes, optimize this kind of distribution in the regular new and delete .

+5
source

Source: https://habr.com/ru/post/976839/


All Articles