C语言中“段错误”出现的场景

1.第一种“段错误”出现的场景
1
/************************************************************************* 2 > File Name: goto.c 3 > Author: Mr.Yang 4 > Purpose:演示goto的用法 (段错误出现的场景) 5 > Created Time: 2017年05月19日 星期五 18时36分23秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 11 int main(void) 12 { 13 int i = 0; 14 int n = 0; 15 start: 16 17 for(i = 0;i<10;i++) 18 { 19 printf("enter a number between 0 and 10:"); 20 scanf("%d",&n);//当接收用户输入时,scanf函数中未加"&"符号,编译能通过,但是会出现“段错误”这样的错误提示 21 if(n >10 || n < 0) 22 { 23 goto start; 24 } 25 else if(n == 0 ) 26 { 27 goto location0; 28 } 29 else if(n == 1) 30 { 31 goto location1; 32 } 33 else 34 { 35 goto location2; 36 } 37 } 38 39 location0: 40 printf("you entered %d\n",n); 41 goto end; 42 43 location1: 44 printf("you entered %d\n",n); 45 goto end; 46 47 location2: 48 printf("you entered between 2 and 10\n"); 49 50 end: 51 52 return 0; 53 }

 

2.第二种“段错误”出现的场景
1
/************************************************************************* 2 > File Name: assert.c 3 > Author: Mr.Yang 4 > Purpose:演示函数assert的用法 5 > Created Time: 2017年05月29日 星期一 19时57分54秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 //#define NDEBUG 可禁用assert。此处当我们禁用assert函数,即把这个地方的#define NDEBUG的注释取消后,也即assert不取作用后 10 #include <assert.h> 11 #include <stdlib.h> 12 13 int main(void) 14 { 15 FILE *fp; 16 17 /*以写的方式打开*/ 18 fp = fopen("test.txt","w"); 19 assert(fp); 20 fclose(fp); 21 22 /*以只读的方式打开*/ 23 fp = fopen("newtest.txt","r");//当禁用assert后,以只读形式打开不存在的文件时,会出现“段错误” 24 assert(fp); 25 fclose(fp);//当禁用assert时程序永远都执行不到这里来 26 27 return 0; 28 }

注:为了不影响理解,此“段错误”总结为:fopen以只读形式打开不存在的文件时,会出现“段错误”

 

posted @ 2017-05-19 18:55  杨来  阅读(3523)  评论(0编辑  收藏  举报