[英]Why this segfault in c program
Can't understand why this segfault in c, valgrind said the fault is at line 25. It is a program to manage a medical studio, when e==1 a patient arrives so it must be added to the queue, e==2 a patient is visited so the first element in queue must be deleted, when e==0 the studio close and the program must print the list of patients remained in alphabetical order and the $. 无法理解为什么在c中出现此段错误,valgrind说故障出在第25行。这是一个管理医疗工作室的程序,当e == 1病人到达时,必须将其添加到队列中,e == 2拜访了一位患者,因此必须删除队列中的第一个元素,当e == 0时,工作室关闭,并且程序必须按字母顺序打印患者列表和$。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN (101)
typedef struct _item {
char *name;
struct _item *next;
} item;
void insert(item* tail, item* next){
item* new = (item*)malloc(sizeof(item));
new->name = (char*)malloc(MAXLEN*sizeof(char));
new->next = NULL;
scanf("%s", new->name);
if (tail == NULL){
tail = new;
next = tail;
}
else
next->next = new;
}
void examination(item *tail){
item *patient;
if (tail->next == NULL)
tail=NULL;
else{
patient = tail;
tail = tail->next;
free(patient);
}
}
int cmp(const void *a, const void *b){
return strcmp(*((char**)a) , *((char**)b));
}
int main(){
int e=1, counter=0, i=0;
item *tail = (item*)malloc(sizeof(item));
item *next;
char **remained;
tail = NULL;
next = tail;
while (e != 0){
scanf("%d", &e);
switch (e){
case 1:
insert(tail, next);
break;
case 2:
examination(tail);
case 0:
break;
default:
return 1;
}
}
next = tail;
while (next != NULL){
counter ++;
next = next->next;
}
next = tail;
remained = (char**)malloc(counter*sizeof(char*));
while(i < counter){
remained[i] = next->name;
next = next->next;
i++;
}
qsort(remained, counter, sizeof(item), cmp);
next = tail;
while (next != NULL){
printf("%s\n", next->name);
next = next->next;
}
printf("$\n");
return 0;
}
if (tail->next == NULL)
传递给tail->next
examination()
的tail->next
未初始化,因为insert()
是通过值而不是通过引用传递指针,也不是从insert()
返回指针,因此基本上为tail
分配了内存,但成员未初始化,因此尝试访问它们将导致不确定的行为,从而导致崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.