More range woes: composed ranges are unsafe to return from functions

monarch_dodra monarchdodra at gmail.com
Tue Oct 16 11:44:56 PDT 2012


On Tuesday, 16 October 2012 at 17:17:36 UTC, Jonathan M Davis
wrote:
> On Tuesday, October 16, 2012 06:40:54 H. S. Teoh wrote:
>> Notice in the second output range, that the third element is 
>> [20, 203]
>> instead of [100, 203], and thereafter a bunch of elements are 
>> skipped,
>> and things just start going haywire after that.
>> 
>> The only difference between the two is that the first is 
>> computed within
>> main(), and the second is returned from a function call. Does 
>> this mean
>> that it's unsafe to return composed ranges from functions?
>
> No. I don't know what's going on, but it sounds like there's a 
> bug somewhere.
>
>> I'm trying to
>> think what might be going wrong. Could it be that the composed 
>> ranges
>> are stack-allocated temporaries that go out of scope upon 
>> returning from
>> the function, so the returned range is actually accessing 
>> invalid
>> memory? (That is a really scary thought.)
>
> If you have a range over static array, then yes, you will have 
> serious issues
> if you return a range over it, because the data is going away, 
> but that's not
> going to happen with a struct or class. The class would be 
> safely on the heap,
> and the struct will get appropriately copied. But one area that 
> could get
> hairy if dmd is buggy is if you're using delegates which access 
> the stack
> frame. It's supposed to work just fine, but it requires that a 
> closure be
> allocated so that the state of the stack frame is saved (and is 
> therefore
> valid after the function call has completed). So, things could 
> definitely go
> funny if there are any bugs in there.
>
> I have no idea what's going wrong for you here (I'd have to 
> spend time
> studying exactly what your code is doing), but there's either a 
> bug in your
> code or a compiler bug which is causing you problems, because 
> aside from
> slices of static arrays, it's perfectly safe to return 
> stack-allocated stuff
> functions - including several layers of ranges.
>
> - Jonathan M Davis

No idea either, but I'll volunteer to investigate ;)

I agree with Jonathan though, sounds like a bug somewhere. There
is no reason for your code to fail.

I'll post back if I find anything.


More information about the Digitalmars-d mailing list