Is it possible to assumeSafeAppend malloced memory?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 19 06:55:00 PDT 2014


On Mon, 19 May 2014 09:44:44 -0400, monarch_dodra <monarchdodra at gmail.com>  
wrote:

> On Monday, 19 May 2014 at 06:08:18 UTC, Ali Çehreli wrote:
>> We know that most of the time memory is allocated more than the  
>> requested amount. Is there a way to take advantage of that extra  
>> trailing space? (And potentially the pages that come after that.)
>>
>> import core.memory;
>>
>> void main()
>> {
>>     const count = 1;
>>
>>     // I think there is extra capacity beyond the 'count' elements
>>     int* ptr = cast(int*)GC.malloc(count * int.sizeof);
>>     int[] arr = ptr[0 .. count];
>>
>>     assert(arr.capacity == 0);
>>     arr.assumeSafeAppend;
>>     assert(arr.capacity == 0);    // still 0. :(
>> }

This is because a block must contain 'used' information in order for  
capacity and assumeSafeAppend to work. This is enabled not only by adding  
the flag APPENDABLE to the allocation (or you can set the attribute  
later), but you must ALSO properly set up the 'used' field. This is best  
left to druntime. The mechanism to store the used size may change in the  
future.

Is there a reason you wouldn't want to do int[] arr = new int[count]? It's  
technically the same call.

>>
>> This issue puts std.array.array to a disadvantage compared to proper  
>> slices because array() involves the following call chain, the last of  
>> which does call GC.malloc:
>>
>>   trustedAllocateArray
>>   uninitializedArray
>>   arrayAllocImpl

This is a bug. arrayAllocImpl should alloc using the proper functions and  
flags.

auto arr = array(1, 2, 3);
assert(arr.capacity != 0); // should pass

> Recently, a new function in druntime was added: "_d_newarrayU".
>
> This void allocates a new array *with* appendable information. We can  
> hope it will be given a more formal and public interface, and it would  
> then be useable by array and/or Appender, to produce slices that have  
> appendable data.

Cool, I didn't know this!

-Steve


More information about the Digitalmars-d-learn mailing list