在下面的代码中,我展示了如何完全按照我的目标来处理上面的问题。它依赖于此处提到的 Mac OSX 扩展和此处描述的信号值
。
我不是这两个主题的专家,所以不能断言这段代码的可移植性。但它确实做了我想要的两件事:它允许我将数据初始化为“NAN”,然后捕获这些未初始化值的无效使用。正常执行和 gdb 都会检测到陷阱。
我当然会感谢对此解决方案的任何评论。
#include "fp_exception_glibc_extension.h"
#include <fenv.h>
#include <signal.h>
#include <stdio.h>
/*
-----------------------------------------------------------------------
This example illustrates how to initialize data with an sNAN. Later, if
the data is used in its 'uninitialized' state, an exception is raised,
and execution halts.
The floating point exception handler 'fp_exception_glibc_extension' is
needed for OS X portability.
At least two blog posts were used in writing this :
"Update: Floating-point exception handling on Mac OS X"
http://philbull.wordpress.com/2012/12/09/update-floating-point-exception-handling-on-mac-os-x/
Note : there is a lengthy email exchange about how portable this extension is; see
comments in the text of the code.
"NaNs, Uninitialized Variables, and C++"
http://codingcastles.blogspot.fr/2008/12/nans-in-c.html
-----------------------------------------------------------------------
*/
void set_snan(double& f)
{
*((long long*)&f) = 0x7ff0000000000001LL;
}
int main()
{
/* On OS X, this extension is provided by
'fp_exception_glibc_extension.{c,h} */
feenableexcept(FE_INVALID);
double p;
set_snan(p); /* Initialize to signaling nan */
double q;
q = 2*p; /* Floating point exception is trapped here */
printf("p = %f; q = %f\n",p,q);
}