Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting dynamically allocated array size

In "The C++ Programming Language" book Stroustrup says:

"To deallocate space allocated by new, delete and delete[] must be able to determine the size of the object allocated. This implies that an object allocated using the standard implementation of new will occupy slightly more space than a static object. Typically, one word is used to hold the object’s size.

That means every object allocated by new has its size located somewhere in the heap. Is the location known and if it is how can I access it?

like image 685
slaviber Avatar asked Oct 29 '25 05:10

slaviber


1 Answers

In actual fact, the typical implementation of the memory allocators store some other information too.

There is no standard way to access this information, in fact there is nothing in the standard saying WHAT information is stored either (the size in bytes, number of elements and their size, a pointer to the last element, etc).

Edit: If you have the base-address of the object and the correct type, I suspect the size of the allocation could be relatively easily found (not necessarily "at no cost at all"). However, there are several problems:

  1. It assumes you have the original pointer.
  2. It assumes the memory is allocated exactly with that runtime library's allocation code.
  3. It assumes the allocator doesn't "round" the allocation address in some way.

To illustrate how this could go wrong, let's say we do this:

size_t get_len_array(int *mem)
{
   return allcoated_length(mem);
}

... 
void func()
{
    int *p = new int[100];
    cout << get_len_array(p); 
    delete [] p;
}

void func2()
{
    int buf[100];
    cout << get_len_array(buf); // Ouch!
}
like image 64
Mats Petersson Avatar answered Oct 31 '25 19:10

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!