Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of dynamically allocated array

Is it true that a pointer assigned to the starting address of a dynamically allocated array does not have the information of the size of the array? So we have to use another variable to store its size for later processing the array through the pointer.

But when we free the dynamically allocated array, we don't specify the size, instead we just "free ptr" or "delete [] ptr". How could free or delete know the size of the array? Can we use the same scheme to avoid storing the size of the array in another variable?

Thanks!

like image 643
Tim Avatar asked Jan 09 '10 18:01

Tim


People also ask

How do you determine the size of a dynamically allocated array?

T *p = new T[count]; size_t size = (char*)&(p[count]) - (char*)p; This gives the size of real data but not any extra size that could has been allocated by the compiler.

Can a dynamically allocated array change size?

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.

What is a dynamically sized array?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.

What is dynamically allocated array?

Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).


1 Answers

Yes, this is true.

delete knows the size of the memory chunk because new adds extra information to the chunk (usually before the area returned to the user), containing its size, along with other information. Note that this is all very much implementation specific and shouldn't be used by your code.

So to answer your last question: No - we can't use it - it's an implementation detail that's highly platform and compiler dependent.


For example, in the sample memory allocator demonstrated in K&R2, this is the "header" placed before each allocated chunk:

typedef long Align; /* for alignment to long boundary */

union header { /* block header */
  struct {
    union header *ptr; /* next block if on free list */
    unsigned size; /* size of this block */
  } s;

  Align x; /* force alignment of blocks */
};

typedef union header Header;

size is the size of the allocated block (that's then used by free, or delete).

like image 101
Eli Bendersky Avatar answered Sep 22 '22 23:09

Eli Bendersky