SegFault trying to chunk lazily joined ranges

Keivan Shah keivan.shah at silverleafcaps.com
Thu Jul 1 14:56:41 UTC 2021


Hello,

I am trying to create a lazy range that iterates and chunks data 
over an array of lazy ranges but the code seems to lead to 
segFaults. I have tried to reduce the issue to minimum possible 
code that reproduces the error. My hypothesis is I am doing 
something wrong leading to the `joiner` and `chunkBy` code to not 
play well with each other, when trying to create a lazy range. 
But the code does work when I load all the data into memory i.e 
skip doing it lazily. Here is the reduced code example, running 
the code on [run.dlang.io](https://run.dlang.io/is/wfhNrn) also 
reproduces the error:

```D
void main()
{
     import std.range;
     import std.stdio;
     import std.algorithm;
     import etc.linux.memoryerror;
     static if (is(typeof(registerMemoryErrorHandler)))
         registerMemoryErrorHandler();

     ForwardRange!(int)[] listOfRanges;
     listOfRanges ~= iota(1).map!(a => a).inputRangeObject;
     listOfRanges ~= iota(2).map!(a => a).inputRangeObject;
     auto lazyFlattenedRange = joiner(listOfRanges);
     auto d1 = lazyFlattenedRange
                 .array // Everything is loaded, no longer lazy
                 .chunkBy!(a => a).map!(a => a[0])
                 .inputRangeObject;
     writeln("Non Lazy Chunked Data length: ", d1.walkLength);

     // The NEXT part will cause a SEGFAULT.
     lazyFlattenedRange = joiner(listOfRanges); // Reinitializing, 
since we already iterated it once
     auto d2 = lazyFlattenedRange
                 .chunkBy!(a => a).map!(a => a[0])
                 .inputRangeObject;
     writeln("Lazy Chunked Data length: ", d2.walkLength); // <--- 
SegFault
}
```
Using the handler I was able to get the stack trace and it seems 
that the segFault is caused by `joiner` trying to call `.save` on 
a null object leading to a `NullPointerError`. But I have not 
been able to debug it further. Mostly it seems that there is 
something wrong with my understanding of ranges or it could be a 
genuine bug in std.range.
Can anyone help me debug this piece of code?

Thanks,
Keivan Shah


More information about the Digitalmars-d-learn mailing list