Bug 12013 – static array of chars implicitly converts to string

Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-01-27T13:03:00Z
Last change time
2014-01-28T01:38:24Z
Keywords
accepts-invalid
Assigned to
nobody
Creator
destructionator

Comments

Comment #0 by destructionator — 2014-01-27T13:03:36Z
// note: this is NOT pure, so it isn't the pure != unique bug char[8] test() { char[8] tmp; tmp[0 .. 8] = "deadbeef"; // fill it with something printable return tmp; } string wtf() { return test(); // this isn't sane! } void main() { string a = wtf(); assert(0, a); // prints garbage; it points to reused stack data } This also affects Phobos std.digest, which returns a static array of chars with toHexString.
Comment #1 by destructionator — 2014-01-27T13:04:36Z
I tested btw on linux DMD32 D Compiler v2.064 (It is the most recent released (non-beta) zip.)
Comment #2 by bearophile_hugs — 2014-01-27T13:14:26Z
It's not just a problem with char[]/string, it's a more general problem (Rust language has a type system designed to prevent such bugs statically): int[6] foo() { return [10, 20, 30, 40, 50, 60]; } int[] bar() { return foo; } void main() { import std.stdio; bar.writeln; } One output: [4202649, 10, 6, 1244636, 1244668, 4202623]
Comment #3 by destructionator — 2014-01-27T13:45:59Z
The D language also has a type system that should catch such problems statically... but I think this is three bugs coming together: 1) static arrays are implicitly sliced. i think this is a mistake since it doesn't let you easily keep track of where the references are going. It is easy enough to do [] when you want one. 2) it is an implicit cast from mutable to immutable. Generally ok since static arrays are value types, but when combined with the implicit slice it is a problem. 3) it is an escaping reference to stack data. This isn't supposed to be allowed in D I think. char[8] => string alone should be illegal but it might do: char[8] => immutable(char[8]), which makes sense alone in the same way int => immutable(int) is logical but then auto slice it, immutable(char[8]) => immutable(char)[]... and now we've entered insanity.
Comment #4 by yebblies — 2014-01-28T01:38:24Z
*** This issue has been marked as a duplicate of issue 9279 ***