我有一个GCC优化错误或C code问题? [英] Do I have a gcc optimization bug or a C code problem?
问题描述
测试以下code:
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
主要()
{
为const char * yytext中=0;
常量浮动F =(浮点)ATOF(yytext中);
为size_t T = *((*为size_t)及F)。
的printf(T应为0,但为%d \\ n,T);
}
与编译:
GCC -O3 test.c的
良好的输出应该是:
T应该是0,但0
但是我的gcc 4.1.3,我有:
T应该是0,但-1209357172
使用编译器标志-fno严格走样。
通过严格别名启用,因为它是默认,至少-O3,在该行:
为size_t T = *((*为size_t)及F)。
编译器假定为size_t *没有指向相同的内存区为浮动*。据我所知,这是符合标准的行为(与坚持围绕GCC-4的ANSI标准开始严格别名规则,托马斯Kammeyer指出)。
如果我没有记错,您可以使用一个中间铸为char *来解决这个问题。 (编译器假定字符*可以别名任何东西)
在换句话说,试试这个(现在不能测试它自己,但我认为这将工作):
为size_t T = *((为size_t *)(字符*)及F);
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);
这篇关于我有一个GCC优化错误或C code问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!