Manually-allocated memory and maximum array capacity

Artur Skawina art.08.09 at gmail.com
Fri Apr 4 17:18:32 PDT 2014


On 04/05/14 00:54, Joseph Rushton Wakeling wrote:
> Hello all,
> 
> If we change the length of a dynamic array using the normal GC-based methods, e.g. by setting the array's .length property, we find that the array's capacity typically does not simply equal the length, but some greater value; there is excess allocation.
> 
> Question: is there a comparable phenomenon for memory that is manually allocated using malloc?  That is, that if we specify a particular number of bytes to allocate, it may be rounded up to a particular larger number?
> 
> And, if so -- is there any way of guaranteeing what that larger number will be?
> 
> The reason I ask is because, suppose that I use a dynamic array as a fixed-size buffer, and that its minimum size must be n.  So, I can do:
> 
>     arr.length = n;
>     if (arr.capacity > arr.length)
>     {
>         arr.length = arr.capacity;
>     }
> 
> ... and get the largest possible buffer that is at least size n, but does not allocate any more memory than setting length = n.
> 
> I'm wondering if I can do something similar with manual memory allocation.

Not portably, as it will be libc and/or allocator specific.

For example, for glibc this would work:

   /* static if (using_glibc) */
   size_t capacity(const void* p) @property @safe { 
      return malloc_usable_size(p);
   }

artur


More information about the Digitalmars-d-learn mailing list