Bug 12980 – Undefined behavior: Assignment of static string to dynamic string
Status
RESOLVED
Resolution
INVALID
Severity
major
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Mac OS X
Creation time
2014-06-24T11:02:00Z
Last change time
2014-06-24T12:13:56Z
Assigned to
nobody
Creator
yuriy.glukhov
Comments
Comment #0 by yuriy.glukhov — 2014-06-24T11:02:27Z
import std.stdio;
char[10] getSomeString()
{
char[10] result;
int i = 0;
for (char a = '0'; a <= '9'; ++a)
{
result[i++] = a;
}
return result;
}
class A
{
this()
{
m = getSomeString();
}
string m;
}
void main()
{
A a = new A();
writeln("STRING: ", a.m); // At this point a.m points to somewhere in stack and thus contains invalid value.
}
Comment #1 by bearophile_hugs — 2014-06-24T11:15:40Z
(In reply to Yuriy from comment #0)
> char[10] getSomeString()
> {
> char[10] result;
> int i = 0;
> for (char a = '0'; a <= '9'; ++a)
> {
> result[i++] = a;
> }
> return result;
> }
D is not fully memory-safe. A starting point to avoid such troubles is to require a [] at that return point:
}
return result[];
}
Comment #2 by issues.dlang — 2014-06-24T11:25:41Z
This code is perfectly legal. It just isn't safe. And if @safe were properly implemented with regards to slicing static arrays, and you marked your code here with @safe, then the compiler would generate an error when the static array was sliced. Unfortunately however, slicing static arrays is currently a hole in @safe:
https://issues.dlang.org/show_bug.cgi?id=8838
But regardless, there's no bug in the language in your example, just in your code. It's not marked with @safe, so it's @system, so even if bug# 8838 were fixed, your code would still compile, because @system code is not checked for memory safety, and it's perfectly possible to do unsafe things with memory in @system code.
Comment #3 by yuriy.glukhov — 2014-06-24T11:38:16Z
Ah, ok. Initially the bug was found when using std.digest.toHexString instead of getSomeString in my example. So should we add a @safe to toHexString and then wait for 8838 fix?
Comment #4 by bearophile_hugs — 2014-06-24T12:13:56Z
(In reply to Yuriy from comment #3)
> Ah, ok. Initially the bug was found when using std.digest.toHexString
> instead of getSomeString in my example.
Yes toHexString returns an array by value. This is not common in D APIs. As more and more D code returns small arrays by value (to allow them to be @nogc and increase performance), this kind of problems and bugs will become sufficiently common that D programmers will be more aware of them and so they will avoid them... :-)