https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106843

            Bug ID: 106843
           Summary: gcc with -O2 corrupt data on stack
           Product: gcc
           Version: 11.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gcc at linuxmotors dot com
  Target Milestone: ---

Compile the following file named t.c with
gcc -O2 t.c -o t
Then run with ./t
it will print out
0 0 401060 0
or some other unexpected data. Without -O2 it prints out the correct
1 2 3 4
gcc 7.5.0 also handles this code fine with or without -O2

#include <stdio.h>
struct rect {
        int x,y,w,h;
};
void test(struct rect *r) {
        if(!r) r=&(struct rect){1,2,3,4};
        printf("%x %x %x %x\n", r->x, r->y, r->w, r->h);
}
int main(int argc, char **argv) {
        test(0);
}


I don't know if this is useful but an objdump of the code produced is this:
0000000000401140 <test>:
  401140:       48 8d 44 24 e8          lea    -0x18(%rsp),%rax
  401145:       48 85 ff                test   %rdi,%rdi
  401148:       48 0f 44 f8             cmove  %rax,%rdi
  40114c:       31 c0                   xor    %eax,%eax
  40114e:       8b 4f 08                mov    0x8(%rdi),%ecx
  401151:       8b 57 04                mov    0x4(%rdi),%edx
  401154:       44 8b 47 0c             mov    0xc(%rdi),%r8d
  401158:       8b 37                   mov    (%rdi),%esi
  40115a:       bf 04 20 40 00          mov    $0x402004,%edi
  40115f:       e9 cc fe ff ff          jmp    401030 <printf@plt>
  401164:       66 2e 0f 1f 84 00 00    cs nopw 0x0(%rax,%rax,1)
  40116b:       00 00 00 
  40116e:       66 90                   xchg   %ax,%ax

It looks like the structure is being referenced on the stack but the optimizer
removed the initialization or something.

It's a linux box.
/proc/cpuinfo starts with this:
processor       : 6
vendor_id       : GenuineIntel
cpu family      : 6
model           : 94
model name      : Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz
stepping        : 3

/etc/os-release is this:
NAME=Slackware
VERSION="15.0"
ID=slackware
VERSION_ID=15.0
PRETTY_NAME="Slackware 15.0 x86_64"
ANSI_COLOR="0;34"
CPE_NAME="cpe:/o:slackware:slackware_linux:15.0"
HOME_URL="http://slackware.com/";
SUPPORT_URL="http://www.linuxquestions.org/questions/slackware-14/";
BUG_REPORT_URL="http://www.linuxquestions.org/questions/slackware-14/";
VERSION_CODENAME=stable

Reply via email to