Segmentation fault (core dumped)

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: 
");
 15     for(ptr = arr+ARRAY_SIZE-1; ptr >= arr; ptr--){
 16         printf("%d 	",*ptr);
 17     }
 18 
 19     printf("
");
 20     return 0;
 21 }


Segmentation fault (core dumped)通常是对内存操作不当造成的,常见的有:

(1)数组超出范围

(2)改动了仅仅读内存。

(3)还有本例也是改动了仅仅读内存。







原文地址:https://www.cnblogs.com/gavanwanggw/p/6740937.html