superbem
superbem

Reputation: 479

gcc optimization flag break code

This code works fine when no optimization flag are set:

#include <cstdio>
int main(){
  float *ptr = ({float var[10] = {1,2,3,4,5,6,7,8,9,10}; var;});
  float *ptr1 = ({float var[10]; for(int i_=0;i_<10;i_++)var[i_]=i_+1; var;});
  float *ptr2 = ({float var[10]; var[4]=5; var;});
  printf("\n value = %f %f %f",ptr[4],ptr1[4],ptr2[4]);
}

It returns 5 5 5 as expected. But when optimization flag are set, it returns 5 0 5.

ptr1 have problem something related to the loop. Why? Maybe its a bug?

I'm using the latest, 4.8.0, tested x64, x86 as well other builds. All same behaviour.

Upvotes: 1

Views: 897

Answers (2)

corahm
corahm

Reputation: 141

The values pointed to by var are allocated on the stack. However, var's scope is the brackets that it is contained within. Setting a pointer to var results in undefined behaviour. As you have seen, in most cases the values in the stack have not changed by the time you print them. However, this can change with different optimization settings. This is not a bug. It is just the nature of undefined behaviour.

Upvotes: 2

Cubbi
Cubbi

Reputation: 47428

You're using a GNU language extension, so let's look at the GNU documentation:

In a statement expression, any temporaries created within a statement are destroyed at that statement's end.

var is destroyed every time, and a pointer to its first element (which is what's returned by the expressions) is not safe to dereference.

Upvotes: 8

Related Questions