Bug 1685 – Array index is evaluated twice

Status
RESOLVED
Resolution
FIXED
Severity
critical
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
All
Creation time
2007-11-22T14:01:00Z
Last change time
2015-06-09T01:14:21Z
Keywords
wrong-code
Assigned to
bugzilla
Creator
i.kasiuk

Comments

Comment #0 by i.kasiuk — 2007-11-22T14:01:09Z
Under certain circumstances, an array index is evaluated twice: $ cat test1.d import std.stdio; int f() { writefln("f()"); return 0; } void main() { int[1] a; a[f()] += 42L; } $ dmd test1.d -oftest1 gcc test1.o -o test1 -m32 -Xlinker -L/opt/dmd/bin/../lib -lphobos2 -lpthread -lm $ ./test1 f() f() $ If the line "a[f()] += 42L;" is replaced by "a[f()] = 42L;" or "a[f()] += 42;" then f() is called only once.
Comment #1 by casio_fifty — 2007-11-23T08:37:25Z
Can be reproduce on Windows with DMD too. Both v1.023 & v2.007 are affected. It seems that the line is interpreted as /*1*/ a[f()] /*2*/ + cast(int)42L /*3*/ -> a[f()] f() is evaluated twice only when a downward cast is needed, so replacing 42L by 42.0 will trigger the 2nd f(), but simpler types such as bool and char won't. Also affects other *= methods, and associative arrays.
Comment #2 by i.kasiuk — 2008-03-01T12:40:05Z
The bug is still present in version 2.011. It's especially dangerous with float arrays, e.g. f[i++] += 0.1; will result in i being incremented by 2 (and the wrong element of f[] being incremented by 0.1).
Comment #3 by witold.baryluk+d — 2008-12-17T13:06:29Z
f[i++] += 0.1; example is really critical for "float[] f". Please add this to DStress. I have many codes in template versions (both for float and double), but most literals and functions returns double which then need implicit cast for floats. This bug makes version for floats very very broken code. I have no idea in what places this bug was silently corrupting my data.
Comment #4 by bugzilla — 2008-12-25T04:37:37Z
Fixed dmd 1.038 amd 2.022