使用GCC和bool指针的条件运算符的结果很奇怪 [英] Weird results for conditional operator with GCC and bool pointers

查看:79
本文介绍了使用GCC和bool指针的条件运算符的结果很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我 memset()一个 stdbool.h bool 变量的值 123 。 (也许这是未定义的行为吗?)然后,我将指向该变量的指针传递给受害者函数,该函数试图使用条件操作来防止出现意外值。但是,由于某些原因,GCC似乎完全删除了条件操作。

In the following code, I memset() a stdbool.h bool variable to value 123. (Perhaps this is undefined behaviour?) Then I pass a pointer to this variable to a victim function, which tries to protect against unexpected values using a conditional operation. However, GCC for some reason seems to remove the conditional operation altogether.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

void victim(bool* foo)
{
    int bar = *foo ? 1 : 0;
    printf("%d\n", bar);
}

int main()
{
    bool x;
    bool *foo = &x;
    memset(foo, 123, sizeof(bool));
    victim(foo);
    return 0;
}




user@host:~$ gcc -Wall -O0 test.c
user@host:~$ ./a.out 
123

这是什么原因特别令人讨厌的是 victim()函数实际上在库中,如果值大于1,则会崩溃。

What makes this particularly annoying is that the victim() function is actually inside a library, and will crash if the value is more than 1.

转载于GCC版本4.8.2-19ubuntu1和4.7.2-5。

Reproduced on GCC versions 4.8.2-19ubuntu1 and 4.7.2-5. Not reproduced on clang.

推荐答案


(也许这是未定义的行为?)

(Perhaps this is undefined behaviour?)

不是直接的,而是随后读取对象。

Not directly, but reading from the object afterwards is.

引用C99:


6.2.6类型表示

6.2.6.1 General

5某些对象表示形式不必表示对象类型的值。如果存储的对象
值具有这种表示形式,并且由不包含
的字符类型的左值表达式读取,则该行为未定义。 [...]

5 Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...]

基本上,这意味着,如果特定实现决定了 bool 分别是 0 1 ,那么您最好确保不要不要使用任何欺骗手段尝试将其设置为其他任何值。

Basically, what this means is that if a particular implementation has decided that the only two valid bytes for a bool are 0 and 1, then you'd better make sure you don't use any trickery to attempt to set it to any other value.

这篇关于使用GCC和bool指针的条件运算符的结果很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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