Do I have a gcc optimization bug or a C code problem?

本文探讨了GCC编译器在-O3优化级别下遇到的一个有趣问题:当尝试将浮点数变量的地址强制转换为size_t类型时,输出结果不符合预期。文章解释了如何通过使用-fno-strict-aliasing标志或通过中间char*指针转换来解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/83962/do-i-have-a-gcc-optimization-bug-or-a-c-code-problem

Test the following code:
#include <stdio.h>
#include <stdlib.h>
main()
{
const char *yytext="0";
const float f=(float)atof(yytext);
size_t t = *((size_t*)&f);
printf("t should be 0 but is %d\n", t);
}


Compile it with:
gcc -O3 test.c

The GOOD output should be:
"t should be 0 but is 0"

But with my gcc 4.1.3, I have:
"t should be 0 but is -1209357172"


Use the compiler flag -fno-strict-aliasing.

With strict aliasing enabled, as it is by default for at least -O3, in the line:
size_t t = *((size_t*)&f);

the compiler assumes that the size_t* does NOT point to the same memory area as the float*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out).

If I recall correctly, you can use an intermediate cast to char* to get around this. (compiler assumes char* can alias anything)

In other words, try this (can't test it myself right now but I think it will work):
size_t t = *((size_t*)(char*)&f);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值