一、某些变量的未初始化导致段错误
二、输入超出范围
当写程序时,要求输入N个数,如果未考虑N<=0的情况,极有可能导致段错误,像如下例题
7-1 单链表的创建及遍历 (30分)
读入n值及n个整数,建立单链表并遍历输出。
输入格式:
读入n及n个整数。
输出格式:
输出n个整数,以空格分隔(最后一个数的后面没有空格)。
输入样例:
在这里给出一组输入。例如:
2
10 5
输出样例:
在这里给出相应的输出。例如:
10 5
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node
{
int data;
struct node* next;
}*head=NULL,*p1=NULL,*p2=NULL;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
head->data = 0;
p2=p1 = head;
int n=0, i = 0;
scanf("%d", &n);
if(n<=0)return 0;
while (i++ < n)
{
p2 = (struct node*)malloc(sizeof(struct node));
scanf("%d", &p2->data);
p1->next = p2;
p1 = p1->next;
p2->next = NULL;
}
i = 0;
head = head->next;
while (head->next!=NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("%d", head->data);
return 0;
}
刚开始,未加if(n<=0)return 0;
,导致一直段错误。