简体   繁体   English

gcc优化标志中断代码

[英]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. 它按预期返回5 5 5 But when optimization flag are set, it returns 5 0 5 . 但是,设置优化标志后,它将返回5 0 5

ptr1 have problem something related to the loop. ptr1有问题与循环有关。 Why? 为什么? Maybe its a bug? 也许是一个错误?

I'm using the latest, 4.8.0, tested x64, x86 as well other builds. 我正在使用最新的4.8.0,经过测试的x64,x86以及其他构建。 All same behaviour. 都是一样的行为。

You're using a GNU language extension, so let's look at the GNU documentation : 您正在使用GNU语言扩展,因此让我们看一下GNU文档

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. var每次都会被销毁,并且指向其第一个元素(由表达式返回的内容)的指针不安全地取消引用。

The values pointed to by var are allocated on the stack. var指向的值分配在堆栈上。 However, var's scope is the brackets that it is contained within. 但是,var的范围是包含在其中的括号。 Setting a pointer to var results in undefined behaviour. 设置指向var的指针会导致未定义的行为。 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. 这只是不确定行为的本质。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM