Sure, but then you deserve what you get...
Posted May 24, 2011 16:48 UTC (Tue) by
farnz (guest, #17727)
In reply to:
Sure, but then you deserve what you get... by marcH
Parent article:
What Every C Programmer Should Know About Undefined Behavior #3/3
Reading the bug report, GCC specifically takes advantage of the undefinedness of signed overflow. We start with the following code (all code in a C-like pseudocode):
int *value;
int i;
int val = 0x03020100;
for (i = 0; i < 256/4; i++) {
value[i] = val;
val += 0x04040404;
}
Step 1 of the failure determines that the only time val equals 0x04030200 is when the loop exit condition is true. It thus rewrites the program to look as if the programmer had written:
int *value;
int i;
int val = 0x03020100;
for (i = 0; val != 0x04030200; i++) {
value[i] = val;
val += 0x04040404;
}
Next, GCC detects that in the absence of overflow, (val != 0x04030200) is always true. It thus rewrites the program to look as if the programmer had written:
int *value;
int i;
int val = 0x03020100;
for (i = 0; true; i++) {
value[i] = val;
val += 0x04040404;
}
This code then translates using the naïve interpretation to the assembler output in the bug report. Note that a finite loop has become infinite; this is a useful optimization because it's not uncommon for real world code to have conditionals that depend solely on constants, such that for this build, the conditional is always true or always false.
(
Log in to post comments)