Segmentation fault (core dumped)
小编一个不小心,将以下程序在11行scanf()中把 ptr 写成了 *ptr,在编译时没问题,但在运行时出现:
$/test/src/$ gcc -o app reverse.c -g $/test/src/$ ./app Enter 3 number :12 13 14 Segmentation fault (core dumped)
示例代码如下:reverse.c
1 #include <stdio.h>
2 #define ARRAY_SIZE 3
3
4 int main(void){
5 int arr[ARRAY_SIZE];
6 int *ptr;
7
8 printf("Enter %d number :",ARRAY_SIZE);
9 for(ptr = arr; ptr < arr+ARRAY_SIZE; ptr++){
10 scanf("%d",*ptr); //是什么原因导致段错误呢? 思考一下
11 //scanf("%d",ptr);
12 }
13
14 printf("The number will output in reversal order: \n");
15 for(ptr = arr+ARRAY_SIZE-1; ptr >= arr; ptr--){
16 printf("%d \t",*ptr);
17 }
18
19 printf("\n");
20 return 0;
21 }
Segmentation fault (core dumped)一般是对内存操作不当造成的,常见的有:
1 #include <stdio.h>
2 #define ARRAY_SIZE 3
3
4 int main(void){
5 int arr[ARRAY_SIZE];
6 int *ptr;
7
8 printf("Enter %d number :",ARRAY_SIZE);
9 for(ptr = arr; ptr < arr+ARRAY_SIZE; ptr++){
10 scanf("%d",*ptr); //是什么原因导致段错误呢? 思考一下
11 //scanf("%d",ptr);
12 }
13
14 printf("The number will output in reversal order: \n");
15 for(ptr = arr+ARRAY_SIZE-1; ptr >= arr; ptr--){
16 printf("%d \t",*ptr);
17 }
18
19 printf("\n");
20 return 0;
21 }
(1)数组超出范围。
(2)修改了只读内存。
(3)还有本例也是修改了只读内存。

本文通过一个示例程序探讨了Segmentation fault (core dumped)错误,该错误通常由内存操作不当引起,如数组越界、修改只读内存等。在示例中,由于在scanf()函数中误将指针解引用,导致了段错误。通过代码分析,解释了错误的原因并提出了修正方法。
1万+

被折叠的 条评论
为什么被折叠?



