繁体   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