什么是分段故障?它在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).

其他回答

简单地说:分段故障是操作系统向程序发送信号表示已检测到非法内存访问,并正在提前终止程序以防止防止内存损坏。

答案中对“分段错误”有几个很好的解释,但由于分段错误通常会导致内存内容转储,所以我想分享分段错误(核心转储)中“核心转储”部分与内存之间的关系来源:

大约从1955年到1975年,在半导体存储器之前,计算机存储器中的主导技术使用了铜线上的微小磁性甜甜圈。甜甜圈被称为“铁氧体磁芯”,主存储器因此被称为核心存储器或“核心”。

从这里拍摄。

分段错误的简单含义是,您试图访问一些不属于您的内存。当我们尝试在只读内存位置读取和/或写入任务或尝试释放内存时,会发生分段错误。换句话说,我们可以将其解释为某种内存损坏。

下面我提到了程序员所犯的导致分段错误的常见错误。

以错误的方式使用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()时使用错误的格式说明符'

在计算中,分段故障或访问违规是由具有存储器保护的硬件引起的故障或故障状况,通知操作系统该软件已尝试访问内存的受限区域-维基百科

您可能正在使用错误的数据类型访问计算机内存。您的案例可能如下所示:

#include <stdio.h>

int main(int argc, char *argv[]) {
    
    char A = 'asd';
    puts(A);
    
    return 0;
    
}

“asd”->是一个字符链,而不是单个字符的char数据类型。因此,将其存储为字符会导致分段错误。在错误的位置存储一些数据。

将这个字符串或字符链存储为单个字符是为了在圆孔中插入一个方形钉。

由于信号:分段故障(11)而终止

塞格姆。错误与尝试在水下呼吸是一样的,你的肺不适合这样。为一个整数保留内存,然后尝试将其作为另一种数据类型进行操作,这根本不起作用。

“分段错误”表示您试图访问无法访问的内存。

第一个问题是你的论点。main函数应该是int main(int argc,char*argv[]),在访问argv[1]之前,应该检查argc是否至少为2。

此外,由于要向printf传递一个浮点值(顺便说一句,在传递到printf时,它会转换为双精度),因此应该使用%f格式说明符。%s格式说明符用于字符串(以“\0”结尾的字符数组)。