Manually-allocated memory and maximum array capacity

Artur Skawina art.08.09 at gmail.com
Tue Apr 8 07:58:58 PDT 2014


On 04/07/14 22:58, Joseph Rushton Wakeling wrote:
> On 05/04/14 02:18, Artur Skawina wrote:
>> Not portably, as it will be libc and/or allocator specific.
> 
> I think that's fine.  I would be using it in circumstances where it's nice to have if I can get it, not a problem if I can't.  As long as I make appropriate use of version statements to ensure it's only used where available, it should be OK and not affect usability.
> 
>> For example, for glibc this would work:
>>
>>     /* static if (using_glibc) */
>>     size_t capacity(const void* p) @property @safe {
>>        return malloc_usable_size(p);
>>     }
> 
> Thanks! :-)

Just be careful; I used the name 'capacity' because it fit
into your example, but 'capacity' shouldn't be overloaded like
that - it works very differently from the magic built-in property.

The only safe way to use it would be:

   E[] aalloc(E)(size_t l) @trusted {
      if (l<size_t.max/E.sizeof)
         if (auto p = cast(E*)malloc(l*E.sizeof))
            return p[0..malloc_usable_size(p)/E.sizeof];
      return null;
   }

artur


More information about the Digitalmars-d-learn mailing list