大约代码是这样的:
#include <signal.h>
void SegmentationFaultHandler( int signal ) {
if ( signal == SIGSEGV ) {
// how to check here if it's actual null pointer?
Throw( NullPointerException, "Object pointer not set to an instance of an object." );
}
else
Throw( InvalidOperationException, "Signal has been intercepted by wrong function." );
}
int main( ) {
signal( SIGSEGV, SegmentationFaultHandler );
try {
int *i = null;
*i = 0;
...
如果我没有仔细检查指针,或者只是访问了未初始化的数据并尊重它,我该如何检查?
我知道这是可能的,因为调试器可以知道程序试图访问哪个地址。
似乎可以使用在signal.h中声明的_pxcptinfoptrs全局变量在处理程序中检索PEXCEPTION_POINTERS。然后使用以下示例中的指针。
static void sigsegv_handler(int signo)
{
PEXCEPTION_POINTERS excptr = _pxcptinfoptrs;
if (excptr != NULL) {
}
// ...
}
矢量异常处理程序
在windows下,您可以使用矢量异常处理程序。您的处理程序将如下所示:
LONG WINAPI ExceptionFilter( struct _EXCEPTION_POINTERS * pExceptionPointers ) {
然后:
pExceptionPointers->ExceptionRecord->ExceptionCode
是您的异常代码,exception_ACCESS_VIOLATION是您访问无效内存时的异常代码。
pExceptionPointers->ExceptionRecord->ExceptionInformation[0] == 0
在完成读取操作时为true
pExceptionPointers->ExceptionRecord->ExceptionInformation[0] == 1
用于写操作
pExceptionPointers->ExceptionRecord->ExceptionInformation[1]
是发生异常时正在读取/写入的地址
结构化异常过滤
如果您不能使用向量异常处理程序,那么您可以在代码的最低级别添加__try/__except,即在main()中或执行线程函数的位置:
__try {
// Code which might cause access violation or any other hardware exceptions
}
__except(ExceptionFilter(GetExceptionInformation())) {
}