无法理解为什么这个段错误在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;
}
答案 0 :(得分:2)
if (tail->next == NULL)
传递给tail->next
的{{1}}未初始化,因为examination()
是按值传递指针而不是通过引用传递指针,也不是从insert()
返回指针所以基本上{{1}分配内存,但成员没有初始化,你试图访问它们,这将导致未定义的行为,从而导致崩溃。