GCC声明表达问题 [英] GCC Statement Expression Issue

查看:111
本文介绍了GCC声明表达问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请注意这个例子:

  #include< stdio.h> 

int main(void)
{

char * res1 =({
char arr [] = {'h','e', '\0'}; //是char * arr []
arr [0] ='x';
char * ptr = arr;
ptr;
}) ;

$ b $ char * res2 =({
char arr [] = {'h','e','\0'}; //是char * arr [ ]
arr [0] ='X';
char * ptr = arr;
ptr;
});

printf(%s%p\\\
,res1,res1);
printf(%s%p\\\
,res2,res2);

返回0;
}

输出:

 X 0x7fff93098160 
X 0x7fff93098160

我注意到,第一个块中的变量 arr ,第二个块中的变量 arr 取得相同的内存地址。



为什么会发生这种情况?

解决方案

arr 是具有自动存储持续时间的数组对象;它们是语句表达式中的 {...} 封闭块的本地语句。



该局部变量的地址;该地址保存在 res1 和res2 中,并在块结束后使用*,当对象 arr` 这个地址在变量不存在时变为无效,程序的行为是未定义的。



所以不要那样做。


I just read about Statement Expressions Extension in GCC, and I found some unexpected behavior when using it.

Please observe this example:

#include <stdio.h>

int main(void)
{

    char* res1 = ({
                        char arr[] ={'h', 'e', '\0'}; // was char *arr[]
                        arr[0] = 'x';
                        char* ptr = arr;
                        ptr;
                 });


    char* res2 = ({
                        char arr[] ={'h', 'e', '\0'}; // was char *arr[]
                        arr[0] = 'X';
                        char* ptr = arr;
                        ptr;
                 });

    printf ("%s %p\n", res1, res1);
    printf ("%s %p\n", res2, res2);

    return 0;
}

Output:

X 0x7fff93098160
X 0x7fff93098160

I noticing that, the variables arr in first block and arr in second block taking the same memory address.

Why that happening??

解决方案

Both occurrences of arr are array objects with automatic storage duration; they're local to the enclosing block { ... } within the statement expression.

Each statement expression grabs the address of that local variable; that address is saved in res1 and res2and used *after* the end of the block, when the objectarr` no longer exists.

This is the same problem as a function returning the address of a local variable. The address becomes invalid when the variable ceases to exist, and the program's behavior is undefined.

So don't do that.

这篇关于GCC声明表达问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆