我目前正在将代码从RHEL5移植到RHEL6 . 虽然我不同意这样做但我很好奇为什么解除引用const var并尝试更新它会导致RHEL6(g 4.4)而不是RHEL5中的段错误 .
程序很好没有const我只是很好奇关于const变量存储在g 4.4中的特殊之处
这是代码和段错误
#include <math.h>
using namespace std;
const double kPi = 2.0 * acos(0.0);
int main (int argc, char ** argv) {
(*((double *)&kPi)) = 2.0 * acos(0.0);
}
程序接收信号SIGSEGV,分段故障 . 在helloconst.cpp中的main(argc = 1,argv = 0x7fffffffd9b8)中的0x000000000040068e:11 11(*((double *)&kPi))= 2.0 * acos(0.0);缺少单独的debuginfos,请使用:debuginfo-install glibc-2.12-1.80.el6.x86_64 libgcc-4.4.6-4.el6.x86_64 libstdc -4.4.6-4.el6.x86_64
(gdb) bt
#0 0x000000000040068e in main (argc=1, argv=0x7fffffffd9b8) at helloconst.cpp:11
(gdb) list
6 #include <math.h>
7 using namespace std;
8
9 const double kPi = 2.0 * acos(0.0);
10 int main (int argc, char ** argv) {
11 (*((double *)&kPi)) = 2.0 * acos(0.0);
12 }
(GDB)
1 回答
更改
const
变量会调用未定义的行为,编译器可以执行任何他们想要的操作 . 所以有's really nothing to explain, don' t那样做 .