[clang]Assigning an uninitialized array to another array produces undefined behavior with optimization -O1

demo:

#include <stdio.h>

#define N 16

struct tmp
{
    int x;
    int ia[N];
};

__attribute__ ((noinline))
int foo()
{
    struct tmp sb;
    struct tmp *pp = &sb;
    int i, ib[N];
  
    for (i = 0; i < N; i++)
        pp->ia[i] = ib[i];

    /* check results: */  
    for (i = 0; i < N; i++)
       printf("%d : %d\n",pp->ia[i], ib[i]);

    return 0;
}

int main (void)
{ 
    foo();
}

-O0 output:

0 : 0
64 : 64
512 : 512
1024 : 1024
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0
0 : 0

-O1 output:

22087 : 0
240 : 0
0 : 0
194 : 0
0 : 0
-298629769 : 0
32766 : 0
-298629770 : 0
32766 : 0
1274982893 : 0
22087 : 0
-1150885144 : 0
32509 : 0
1274982816 : 0
22087 : 512
0 : 0

even the array is uninitialized, why the two arrays are different with optimization -O1,-O2,etc.

Undefined behavior if “the value of an object with automatic storage duration is used while it is indeterminate” (C99 draft).

2 Likes

thank you