Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When delete [] pointer works, why can't you get the size of the array pointed to?

Tags:

c++

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.

like image 410
Prokop Hapala Avatar asked Aug 04 '17 10:08

Prokop Hapala


People also ask

How does delete [] work in C?

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.

How does delete [] know how much to delete?

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 would you use the delete [] syntax?

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.

When to use delete [] and delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.


1 Answers

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.

like image 158
Mike Nakis Avatar answered Oct 12 '22 17:10

Mike Nakis