1685 – Array index is evaluated twice

D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 1685 - Array index is evaluated twice
Summary: Array index is evaluated twice
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 All
: P2 critical
Assignee: Walter Bright
URL:
Keywords: wrong-code
Depends on:
Blocks:
Reported: 2007年11月22日 14:01 UTC by Ivo Kasiuk
Modified: 2015年06月09日 01:14 UTC (History)
1 user (show)

See Also:


Attachments
Add an attachment (proposed patch, testcase, etc.)

Note You need to log in before you can comment on or make changes to this issue.
Description Ivo Kasiuk 2007年11月22日 14:01:09 UTC
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 Kenny Chan 2007年11月23日 08:37:25 UTC
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 Ivo Kasiuk 2008年03月01日 12:40:05 UTC
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 Witold Baryluk 2008年12月17日 13:06:29 UTC
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 Walter Bright 2008年12月25日 04:37:37 UTC
Fixed dmd 1.038 amd 2.022


AltStyle によって変換されたページ (->オリジナル) /