什么是分段故障?它在C和C++中不同吗?分段错误和悬挂指针是如何关联的?
当前回答
当程序试图访问不存在的内存位置,或试图以不允许的方式访问内存位置时,会发生分段错误或访问冲突。
/* "Array out of bounds" error
valid indices for array foo
are 0, 1, ... 999 */
int foo[1000];
for (int i = 0; i <= 1000 ; i++)
foo[i] = i;
这里i[1000]不存在,因此出现segfault。
分段故障的原因:
it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
De-referencing NULL pointers – this is special-cased by memory management hardware.
Attempting to access a nonexistent memory address (outside process’s address space).
Attempting to access memory the program does not have rights to (such as kernel structures in process context).
Attempting to write read-only memory (such as code segment).
其他回答
老实说,正如其他海报所提到的那样,维基百科在这方面有一篇很好的文章,所以看看吧。这种类型的错误非常常见,通常称为其他错误,如访问违规或一般保护故障。
它们在C、C++或任何其他允许指针的语言中都没有区别。这些类型的错误通常由以下指针引起:
在正确初始化之前使用在它们指向的内存被重新定位或删除后使用。在索引超出数组边界的索引数组中使用。这通常只在对传统数组或c字符串进行指针计算时发生,而不是基于STL/Boost的集合(在c++中)
分段错误的简单含义是,您试图访问一些不属于您的内存。当我们尝试在只读内存位置读取和/或写入任务或尝试释放内存时,会发生分段错误。换句话说,我们可以将其解释为某种内存损坏。
下面我提到了程序员所犯的导致分段错误的常见错误。
以错误的方式使用scanf()(忘记放&)。
int num;
scanf("%d", num);// must use &num instead of num
以错误的方式使用指针。
int *num;
printf("%d",*num); //*num should be correct as num only
//Unless You can use *num but you have to point this pointer to valid memory address before accessing it.
修改字符串文字(指针尝试写入或修改只读内存。)
char *str;
//Stored in read only part of data segment
str = "GfG";
//Problem: trying to modify read only memory
*(str+1) = 'n';
尝试通过已释放的地址进行访问。
// allocating memory to num
int* num = malloc(8);
*num = 100;
// de-allocated the space allocated to num
free(num);
// num is already freed there for it cause segmentation fault
*num = 110;
堆栈溢出-:堆栈内存不足访问数组超出界限'使用printf()和scanf()时使用错误的格式说明符'
当进程(正在运行的程序实例)试图访问其他进程正在使用的只读内存地址或内存范围或访问不存在的(无效的)内存地址时,会发生分段错误。悬挂引用(指针)问题意味着试图访问内容已从内存中删除的对象或变量,例如:
int *arr = new int[20];
delete arr;
cout<<arr[1]; //dangling problem occurs here
分段错误是由对进程未在其描述符表中列出的页面的请求,或对进程已列出的页面(例如,只读页面上的写入请求)的无效请求引起的。
悬空指针是指可能指向或不指向有效页,但确实指向“意外”内存段的指针。
简单地说:分段故障是操作系统向程序发送信号表示已检测到非法内存访问,并正在提前终止程序以防止防止内存损坏。