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

            Bug ID: 85205
           Summary: Optimalisation fails when using a union to allocate
                    space on stack
           Product: gcc
           Version: 7.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: Mijzelf at gmx dot com
  Target Milestone: ---

The code 

#include <stdio.h>
static int count = 0;
struct X{
        int length;

        struct Y {
                int var1;
                int var2;
        } data[ 1 ];
};

int main( int argc, char **argv )
{
        union {
                X args;
                char dummy[ sizeof( X ) + 6 * sizeof( X::Y ) ];
        };

        printf( "%d sizeof(dummy) = %ld\n", ++count, sizeof(dummy) );

        for( int i=0; i<5; i++ )
        {
                printf( "i:%d\n", i );
                args.data[ i ].var1 = i;
        }

        return 0;
}

with an optimalisation of at least -O2 (g++ -O2 source.cpp) gives as output:

1 sizeof(dummy) = 60
i:0
i:1
2 sizeof(dummy) = 60
i:0
i:1
<snip>
37405 sizeof(dummy) = 60
i:0
i:1
37406 sizeof(dummy) = 60
i:0
i:1
Segmentation fault (core dumped)

If the code is changed so data has 0 elements:

struct X{
        int length;

        struct Y {
                int var1;
                int var2;
        } data[ 0 ];
};

the code works as expected

1 sizeof(dummy) = 52
i:0
i:1
i:2
i:3
i:4

Reply via email to