D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 16454 - Return in the body of a foreach in a constructor backed by opApply corrupts the object
Summary: Return in the body of a foreach in a constructor backed by opApply corrupts t...
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 major
Assignee: No Owner
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2016-08-31 17:45 UTC by André Puel
Modified: 2024-12-13 18:49 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 André Puel 2016-08-31 17:45:38 UTC
import std.stdio;

struct OpApply {
    int opApply(int delegate(int) cb) {
        return cb(42);
    }
}

struct Bolinha {
    int a;
    this(ref OpApply moviadao) {
        foreach(int b; moviadao) {
            this.a = b;
            return;
        }
    }
};

void main() {
    import std.stdio;

    OpApply range;
    writeln(Bolinha(range).a);
}

The expected print result was 42. But I get a random memory garbage instead. The following minor modification in main will 'fix' the issue:

void main() {
    import std.stdio;

    OpApply range;
    Bolinha littleBall = Bolinha(range);
    writeln(littleBall.a);
}
Comment 1 ag0aep6g 2016-08-31 18:14:51 UTC
Slightly reduced:

----
struct OpApply {
    int opApply(int delegate(int) cb) { return 0; }
}

struct Bolinha {
    int a = 0;
    this(int dummy) {
        OpApply moviadao;
        foreach(int b; moviadao) return;
    }
}

void main() {
    import std.stdio;
    writeln(Bolinha(0).a);
}
----

Also fails on Linux and Windows (wine).
Comment 2 moonlightsentinel 2021-10-26 13:19:53 UTC
Works reliably since 2.094.1 according to run.dlang.io / local tests
Comment 3 dlangBugzillaToGithub 2024-12-13 18:49:55 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

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

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