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以只讀形式打開不存在的文件時,會出現“段錯誤”