learn some d those days, can't understand the code here

Junfeng via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 12 12:13:16 PST 2016


Hi,

Come here for help. what I doing is setup vim and use dcd for 
goto define, but sometimes dcd-server got crash, issue is here: 
https://github.com/Hackerpilot/DCD/issues/294

Then I build the debug version, and an assert error comes out:

https://github.com/Hackerpilot/libdparse/blob/master/src/dparse/parser.d#L6654

paste here:

     T[] ownArray(T)(T[] from)
     {
         if (allocator is null)
             return from;
         if (from.length == 0)
             return null;
         T[] to = cast(T[]) allocator.allocate(T.sizeof * 
from.length);
         assert (to.length == from.length, format("from.length = 
%d, to.length = %d", from.length, to.length));
         to[] = from[];
         return to;
     }

For my limited d knowledge, T[] is an array has abi layout:

0: size
size_t: ptr

seems the code try to allocate an array with size from.length, 
but after cast, the length at offset 0 will be 0, so assert 
fail(why dmd allow this cast here? I try use GC.malloc and cast 
in my small test app, dmd will error "Error: cannot cast 
expression malloc(400LU, 0u, null) of type void* to Node[]").

a quick search, seem we should write it like:

t[] to = (cast(T*)allocator.allocate(T.sizeof * from.length))[0 
.. from.length]);

but after this modify, it will crash at
          to[] = from[];





More information about the Digitalmars-d mailing list