一旦一个程序发生了越界访问,cpu 就会产生相应的保护,于是 segmentation fault 就出现了,通过上面的解释,段错误应该就是访问了不可访问的内存,这个内存区要么是不存在的,要么是受到系统保护的,还有可能是缺少文件或者文件损坏。
在C代码,分割错误通常发生由于指针的错误使用,特别是在C动态内存分配。非关联化一个空指针总是导致段错误,但野指针和悬空指针指向的内存,可能会或可能不会存在,而且可能或不可能是可读的还是可写的,因此会导致瞬态错误
#include
int main (void)
{
int *ptr = NULL;
*ptr = 0;
return 0;
}
上述是指针错误使用导致的段错误。
#include
int main (void)
{
int *ptr = (int *)0;
*ptr = 100;
return 0;
}
#include
int main()
{
char *p = "I love C++";
p = "F";
return 0;
}
它试图修改一个字符串文字,这是根据ANSI C标准未定义的行为。
大多数编译器在编译时不会抓,而是编译这个可执行代码,将崩溃。
#include
int main()
{
int *p = NULL;
std::cout << *p << std::endl;
return 0;
}
上述代码想要访问一个空指针的值。在操作系统中,这样将会导致段错误。
#include
#include
#include
using namespace
int main()
{
//malloc动态内存分配,释放、置空完成后,不能继续再使用该指针
char *s = (char* )malloc(100);
s = NULL;
cout << s << endl;
}
#include
#include
int main (void)
{
main ();
return 0;
}
上述代码将导致无限递归,这样将导致堆栈溢出;此时的代码返回语句行为是未经定义的。
这个错误十分常见,例如下述代码:
#include
#include
using namespace std;
void doPrint()
{
double a = 1.99;
vector v;
for(int i = 0; i < 10; i++)
{
v.push_back(a);
}//此时vector数组中有10个元素
vector::iterator it = v.begin();
cout << *(it + 10) << endl;
//注意,此时括号内的指针已经严重越位了,无法访问vector中的元素
}
int main()
{
doPrint();
system("pause");
return 0;
}
文章参考了:https://blog.csdn.net/qq_29350001/article/details/53780697