Segmentation fault 原因总结

先看一个文档中的文字
A segmentation fault (often shortened to SIGSEGV) is a particular error condition that can occur during the operation of computer software.

产生的原因最常见的有以下两点

1.当用户态程序访问(访问表示读、写或执行)不允许访问的内存时,产生SIGSEGV。

访问权限不对

#include<stdio.h>
#include<stdlib.h>

int main(){
    char *c = "hello world";
    c[1] = 'H';
}

"hello world"会被放到代码段,代码段的权限一般都是r-- p所以应该只读的 不可写,所以会导致错误Segmentation fault

访问了不属于进程地址空间的内存

#include <stdio.h>
 
#include <stdlib.h>
 
int main()
 
{
 
    int* p = (int*)0x00008FFFFFFFFFFF;//用户空间最多分配到0x00007FFFFFFFFFFF,看我linux内存划分的那篇博客,这种情况我在实际开发中就真实遇到过,当时还困扰了许久
 
    *p = 10;
 
} 

访问了不存在的内存,最经典就是使用了空指针,可以类比java中的NullPointException,空指针异常

int *p = null;
*p = 10;

java中,就是一个对象的引用指向null,但是却尝试通过这个引用调用对象的方法,就会出现空指针异常(NullPointException)

A a = null;
a.doSomeThing(); //抛出NullPointException

2.当用户态程序以错误的方式访问允许访问的内存时,产生SIGSEGV。

试图把一个整数按照字符串的方式输出
int  main()
 
{
 
        int b = 10;
 
        printf("%s\n", b);
 
        return 0;
 
} 
posted @ 2020-09-09 00:52  驿站Eventually  阅读(6018)  评论(0编辑  收藏  举报