[Issue 23170] Array literal passed to map in lambda, then returned from nested function, is memory corrupted

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jun 7 17:20:30 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=23170

--- Comment #5 from Iain Buclaw <ibuclaw at gdcproject.org> ---
(In reply to FeepingCreature from comment #0)
> Consider this code:
> 
> import std.algorithm;
> import std.conv;
> import std.range;
> 
> void main()
> {
>     auto result = ({ return [1, 2, 3].badMap; })().array;
> 
>     assert(result == [1, 2, 3], result.to!string);
> }
> 
> alias badMap = range => range.map!(a => a);
This is the original, but without imports (could use as an extra test).

---
template map(fun...)
{
    auto map(int[] r)
    {
        static struct MapResult(alias fun)
        {
            this(int[] input) { _input = input; }
            auto length() { return _input.length; }
            bool empty() { return !_input.length; }
            auto ref front() { return fun(_input[0]); }
            void popFront() { _input = _input[1 .. $]; }
            private int[] _input;
        }
        return MapResult!(fun)(r);
    }
}

auto array(Range)(Range r)
{
    const length = r.length;
    if (length == 0) return null;
    int[] result;
    result.length = 3;
    size_t i;
    foreach (e; r)
    {
        result[i] = e;
        ++i;
    }
    assert(i == length);
    return (() @trusted => cast(int[]) result)();
}

void main()
{
    auto result = [1, 2, 3].badMap.dgify()().array;
    assert(result == [1, 2, 3]);
}

alias badMap = range => range.map!(a => a);
alias dgify = (lazy value) => &value;

--


More information about the Digitalmars-d-bugs mailing list