c语言 - 关于 signal() 函数的奇怪'SIGSEGV'性能



我有3个例子来描述我在这里的困惑。

首先,一个经典的分段错误程序是这样的:

#include <stdio.h>
main()
{       
    int *p=NULL;
    *p=0; //here will cause a SIGSEGV signal
}
当我运行上面的applet时,终端将显示
# ./a.out 
Segmentation fault

接下来,我在applet中添加一个signal()函数,然后它看起来像这样:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void handler(int s)
{   
    if(s==SIGSEGV)
        printf("It's SIGSEGV!n");
    exit(1);
}
main()
{   
    int *p=NULL;
    signal(SIGSEGV,handler);
    *p=0;
    return 0;
}   
当我运行上面的applet时,终端将显示
# ./a.out 
It's SIGSEGV!

最后,我删除了applet中的NULL字符串,它将成功运行!!:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void handler(int s)
{   
    if(s==SIGSEGV)
        printf("It's SIGSEGV!n");
    exit(1);
}
main()
{   
    int *p; //There is no more 'NULL' here
    signal(SIGSEGV,handler);
    *p=0;
    printf("The value of p is %dn",*p);
    return 0;
}

结果

# ./a.out 
The value of p is 0

为什么?

对未初始化的指针解引用是未定义的行为。任何事情都有可能发生。程序坏了,你没法跟它讲道理。

最新更新