Bug 12226 – functions can return local stack-allocated objects by reference

Status
RESOLVED
Resolution
WORKSFORME
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-02-22T12:25:43Z
Last change time
2021-09-08T12:56:08Z
Keywords
accepts-invalid, diagnostic
Assigned to
No Owner
Creator
badlink

Comments

Comment #0 by andrea.9940 — 2014-02-22T12:25:43Z
An auto ref function can return a local stack-allocated struct by reference causing undefined behavior when executed. Sample code: http://pastebin.com/rvcNdjAE
Comment #1 by k.hara.pg — 2015-01-11T06:39:30Z
(In reply to badlink from comment #0) > Sample code: http://pastebin.com/rvcNdjAE All sample code should be attached in bugzilla, or directly written in comment. ---------------- import std.stdio; void main() { auto a = Vec3f([0, 0, 0]); a += a * 0; writeln(a.array); // prints random values like [-1.13483, 4.2039e-45, -1.13482] assert(a == Vec3f([0, 0, 0])); // fails } alias Vector!(3, float) Vec3f; struct Vector(int size, T) { T[size] array; auto ref opBinary(string op)(T rhs) const if (op == "+" || op == "-" || op == "*" || op == "/") { Vector vector = this; mixin("return vector" ~ op ~ "= rhs;"); } auto ref opOpAssign(string op)(T rhs) if (op == "+" || op == "-" || op == "*" || op == "/") { mixin("array[] " ~ op ~ "= rhs;"); return this; } auto opOpAssign(string op)(const ref Vector rhs) // auto opOpAssign(string op)(const Vector rhs) // witouth ref everything works if (op == "+" || op == "-") { mixin("array[] " ~ op ~ "= rhs.array[];"); return this; } } ----------------
Comment #2 by dkorpel — 2021-09-08T12:56:08Z
The example doesn't compile today because it's passing an rvalue to a ref parameter, but returning ref variables is now caught by dip25.