Bug 3024 – Array slicing allows returning an escaping reference to a local stack variable

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
All
OS
All
Creation time
2009-05-25T06:32:35Z
Last change time
2018-04-21T12:57:44Z
Assigned to
No Owner
Creator
david

Comments

Comment #0 by davidl — 2009-05-25T06:32:35Z
import std.stdio; string func() { string s="abc"; return s; } void func1() { writefln("func1"); string v = func(); writefln("call func"); writefln(func2()); } byte[] func2() { writefln("hello!"); byte[16] v= [65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65]; writefln(v[0..16]); return v[0..16]; } void main(string[] args) { func1(); }
Comment #1 by 2korden — 2009-05-25T06:45:13Z
It is exactly the same as byte[] tmp = v[0..16]; return tmp; Compiler can't detect operations like this ATM, and is not supposed to (according to specs). Marking it as an enhancement request, I wouldn't hold my breath for this being fixed.
Comment #2 by matti.niemenmaa+dbugzilla — 2009-07-12T08:53:14Z
Also affects 1.0. It's true that the specs don't mention it but it's a bit inconsistent that both the pointer and scope object cases are detected while the case of array slicing isn't. Of the following, currently only the first three result in a compile error: int* pointer() { int x; return &x; } Object object() { scope Object x; return x; } int[] array() { int[1] x; return x; } int[] slice() { int[1] x; return x[]; }
Comment #3 by nick — 2018-04-21T12:57:44Z
(In reply to david from comment #0) > byte[] func2() > { > byte[16] v= [65,65,65,65, > 65,65,65,65, > 65,65,65,65, > 65,65,65,65]; > return v[0..16]; > } This is now fixed (dmd v2.079.1): onlineapp.d(7): Error: returning v[0..16] escapes a reference to local variable v