Segmentation fault in Linux
段错误应该就是访问了不可访问的内存,这个内存要么是不存在的,要么是受系统保护的。
- SIGSEGV是在访问内存时发生的错误,它属于内存管理的范畴
- SIGSEGV是一个用户态的概念,是操作系统在用户态程序错误访问内存时所做出的处理
- 当用户态程序访问(访问表示读、写或执行)不允许访问的内存时,产生SIGSEGV
-
当用户态程序以错误的方式访问允许访问的内存时,产生SIGSEGV
用户态程序地址空间,特指程序可以访问的地址空间范围。如果广义的说,一个进程的地址空间应该包括内核空间部分,只是它不能访问而已。
SIGSEGV产生的可能情况
SIGSEGV在很多时候是由于指针越界引起的,但并不是所有的指针越界都会引发SIGSEGV。一个越界的指针,如果不引用它,是不会引起SIGSEGV的。而即使引用了一个越界的指针,也不一定引起SIGSEGV。
错误的访问类型引起
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ch = "hello world";
ch[1] = 'H';
return 0;
}
访问了不属于进程地址空间的内存
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)0xC0000fff;
*p = 10;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
scanf ("%d", i); /* should be used &i */
printf ("%d\n", i);
return 0;
}
访问了不存在的内存
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = NULL;
*p = 1;
return 0;
}
内存越界,数组越界,变量类型不一致等
#include <stdio.h>
#include <stdlib.h>
int main()
{
char test[1];
printf("%c", test[10]);
return 0;
}
试图把一个整数按照字符串的方式输出
#include <stdio.h>
#include <stdlib.h>
int main()
{
int b = 10;
printf("%s\n", b);
return 0;
}