1
votes

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.

2
Looks like pointers to expired temporaries. - Pubby
Yup, reeks of undefined behaviour. I didn't know this was legal, thoguh, so thanks. - chris
@chris it's a GNU language extension - Cubbi
it is a bug, in your code. you cannot return a pointer of a stack object and use it outside the scope. - Bryan Chen
@Cubbi, Oh, thanks. I didn't realize -pedantic is off by default on Coliru. - chris

2 Answers

8
votes

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.

2
votes

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.