D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 18909 - Lambda with default initializer gets called with random values instead
Summary: Lambda with default initializer gets called with random values instead
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86_64 Linux
: P3 normal
Assignee: No Owner
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2018-05-26 16:12 UTC by Malte
Modified: 2024-12-13 18:58 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Malte 2018-05-26 16:12:25 UTC
The following code should print 2 but writes random numbers instead:

void main() @safe
{
    import std.stdio : writeln;

    writeln(identity(2));
}

int identity(immutable int q) pure nothrow @safe @nogc
{
    import std.algorithm : map;

    static immutable auto arr = [42];
    int getSecondArgument(int a, int b)
    {
        return b;
    }

    return arr.map!((int a, int b = q) => getSecondArgument(a, b))[0];
}
Comment 1 ag0aep6g 2018-05-26 16:37:31 UTC
Reduced Phobos away:

----
void main() @safe
{
    assert(identity(2) == 2); /* fails; should pass */
}

struct Map(alias fun)
{
    int front() @safe { return fun(); }
}

int identity(immutable int q) pure nothrow @safe @nogc
{
    int getArg(int b) @safe
    {
        return b;
    }
    return Map!((int b = q) => getArg(b))().front();
}
----
Comment 2 Hiroki Noda 2019-04-27 07:53:53 UTC
This should fail to compile, and in this case you can use `lazy int b = q` and will work.
Comment 3 dlangBugzillaToGithub 2024-12-13 18:58:54 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/19440

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB