当我用优化(选项-O1,-O2,-O3等)编译它时,我正在编写一个不起作用的C程序(我得到分段错误),但是当我编译它时它工作得很好优化.
我的代码中是否有错误的可能性?或者我应该假设这是GCC中的错误?
我的GCC版本是3.4.6.
这种问题有没有已知的解决方法?
我的程序的优化和未优化版本之间的速度差异很大,所以我真的需要使用优化.
这是我原来的运算符.没有优化级别的工作正常,并且在任何优化级别都会引发分段错误:
struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
return distance(point,p1) < distance(point,p2) ;
}
} ;
并且这个可以完美地适用于任何级别的优化:
struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
float d1=distance(point,p1) ;
float d2=distance(point,p2) ;
std::cout << "" ; //without this line, I get a segmentation fault anyways
return d1 < d2 ;
}
} ;
不幸的是,这个问题难以重现,因为它发生了一些特定的值.我在对超过一千个向量中的一个进行排序时得到了分段错误,所以它实际上取决于每个向量具有的特定值组合.
解决方法:
现在你发布了代码片段并找到了一个工作的解决方法(@Windows程序员的答案),我可以说也许你正在寻找的是-ffloat-store.
-ffloat-store
Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory.
This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables.
资料来源:http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html