2015-04-02 43 views
0

不能理解为什么这个段错误在c中,valgrind说错在第25行。 这是一个管理医疗工作室的程序,当病人到达时== == 1,所以它必须被添加到队列中,e == 2一个病人被访问,所以队列中的第一个元素必须被删除,当e == 0时,演播室关闭,程序必须打印病人列表,并保持按字母顺序和$。为什么在c程序中的段错误

#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; 
} 
+1

插入函数看起来不对[你需要指针指针](http://stackoverflow.com/a/18307020/1673391) – 2015-04-02 08:26:34

+0

第25行是哪一行? – alk 2015-04-02 08:48:08

+0

[请不要强制转换'malloc()']的结果(http://stackoverflow.com/a/605858/3233393)。 – Quentin 2015-04-02 09:33:17

回答

2
if (tail->next == NULL) 

tail->next传递给examination()未初始化,因为insert()你是按值而不是通过引用传递指针也没有返回从insert()所以基本上tail分配内存的指针,但成员不被初始化和你正试图访问它们,这将导致未定义的行为,从而导致崩溃。

+0

如何纠正它? – 2015-04-02 08:30:36

+0

@GrijeshChauhan作为我的答案的一部分,我说'tail'成员需要初始化,并且已经给出了2种方法来完成它。一个将指针指向一个参数,另一个执行'insert()'中的所有操作并返回一个类型为“item”的指针 – Gopi 2015-04-02 08:32:28