A common way to use a heap-allocated array is:
SomeType * arr = new SomeType[15454];
//... somewhere else
delete [] arr;
In order to do delete [] arr
the C runtime has to know the length of the memory buffer associated with the pointer. Am I right?
So in principle it should be possible to access the information somehow? Could it be accessed using some library? I'm just wondering. I understand that it is not a core part of the language so it would be platform dependent.
Master C and Embedded C Programming- Learn as you goDelete[] operator is used to deallocate that memory from heap. New operator stores the no of elements which it created in main block so that delete [] can deallocate that memory by using that number.
The general answer is that the C++ runtime stores the number objects allocated (not the bytes allocated) so that when delete[] is called it can execute the right number of destructors.
When you have an array of objects you need to use delete[] as shown in the example below. std::string *myName=new std::string; std::string *myStrings=new std::string[10]; delete myName; //deletes an object delete[] myString; //deletes an array of object.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
You get it right. The information is there. But there is no standard way of obtaining it.
If you are using windows, there is an _msize()
method, which might give you the size of the memory block, though it may not necessarily be accurate. (The reported memory block size may be rounded up to the closest larger alignment point.) See MSDN -
_msize
If this is something that you really must have, you can try your luck with overriding new
, allocating a slightly larger memory block, storing its size in the beginning, and returning a pointer to the byte after the size. Then you can write your own msize()
which returns that size. Of course you will need to also override delete
. But it is too much hassle, and it is best to avoid it if you can. If that way you go, only pain will you find.
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