2013-11-28 129 views
0

我有這個奇怪的分段錯誤。我試圖找到患者列表中是否已經存在使用指針的患者列表。我認爲有問題的代碼是:C指針分割錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include "health.h" 

void addPatient(int patientID) { 
printf("here1"); 
    Chart* patients_chart; 

    // find the patient with id 
    patients_chart = patientList; 

    while(patients_chart == NULL || patients_chart->id == patientID) { 
     patients_chart = patients_chart->next; 
printf("here2"); 
    } 

printf("here3"); 

    // if patient wasn't found, add new patient 
    if (patients_chart == NULL) { 
     Chart *new_chart; 
printf("here4"); 
     // allocate and initialize new patient 
     new_chart   = (Chart*)malloc(sizeof(Chart)); 
     new_chart->id  = patientID; 
     new_chart->buffer = NULL; 

     // insert new patient into list 
     new_chart->next = patientList; 
     patientList  = new_chart; 
printf("here5"); 
    } 
} 

包含的health.h只是方法聲明和結構。我將在下面列出它們,但請注意,我的任務限制了我修改health.h中的任何代碼。我也會在最後發佈我的代碼。

/* 
* Patient's health chart: ID + linked list of health type readings 
*/ 
typedef struct chartEntry* Chartptr; /* pointer to a Chart */ 

typedef struct chartEntry{ 
    int id;    /* patient ID */ 
    CBuffptr buffer;  /* pointer to first health type buffer */ 
    Chartptr next;   /* pointer to next patient */ 
}Chart; 


extern Chartptr patientList; 

我調用該函數在主與輸入像這樣的:1,12:12:12,7,0

的7設置在 「命令」

1是患者有問題的ID

您可以忽略其餘。

我明白如何找到病人,但我得到這個令人討厭的seg故障。感謝您的時間!

+0

在哪一點你有段錯誤?你的搜索循環條件似乎不好。 – rano

+0

[請不要在C]中輸入'malloc()'的返回值(http://stackoverflow.com/a/605858/28169)。 – unwind

+0

@unwind非常感謝你!你剛剛證明我的教授。在一定程度上錯誤。 – user3043594

回答

2

以下代碼是越野車:

while(patients_chart == NULL || patients_chart->id == patientID) { 
    patients_chart = patients_chart->next; 
    printf("here2"); 
} 

您正在推進,只要任一指針NULL或指針患者ID相匹配。你錯過了否定。相反,使用:

while(patients_chart != NULL && patients_chart->id != patientID) { 
    patients_chart = patients_chart->next; 
    printf("here2"); 
} 
+0

我試過它沒有解決問題。雖然,我的循環邏輯似乎沒有關係。 – user3043594

+0

這解決了我的問題。但它歸結爲指針解引用。 – user3043594

1
while(patients_chart == NULL || patients_chart->id == patientID) { 
    patients_chart = patients_chart->next; 
} 

這裏,如果條件1(patients_chart == NULL)是真實的,那麼你這樣做:
patients_chart = patients_chart->next;

這是空指針引用,從而導致賽格故障。

+0

就是這樣! patients_chart = patientList; (patients_chart!= NULL){ while(patients_chart-> id!= patientID){ patients_chart = patients_chart-> next; } } – user3043594