簡體   English   中英

C指針分割錯誤

[英]C Pointers Segmentation Fault

我遇到這種奇怪的細分錯誤。 我試圖使用指針查找患者列表中是否已存在患者ID。 我認為有問題的代碼是:

#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;

我用以下輸入在main中調用該函數:1,12:12:12,7,0

7是“命令”

1是有問題的患者ID

您可以忽略其余部分。

我知道如何找到病人,但是卻遇到了這種煩人的段錯誤。 感謝您的時間!

以下代碼有錯誤:

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");
}
while(patients_chart == NULL || patients_chart->id == patientID) {
    patients_chart = patients_chart->next;
}

如果條件1( patients_chart == NULL )為true,則執行此操作:
patients_chart = patients_chart->next;

這是空指針取消引用,從而導致段故障。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM