简体   繁体   中英

C Pointers Segmentation Fault

I'm having this strange segmentation fault. I'm trying to find if a patients id already exists in the list of patients using pointers. I think the code in question is:

#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");
    }
}

The included health.h is just method declarations and structs. I will list them below, but please note that my assignment restricts me from modifying any of the code in health.h. I will also post my code at the very end.

/*
*   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;

I call the function in main with input like this one: 1,12:12:12,7,0

The 7 is the "command"

the 1 is the patient id in question

You can ignore the rest.

I understand how to find the patient, but I'm getting this annoying seg fault. Thank you for your time!

The following code is buggy:

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

You are advancing for as long as either the pointer is NULL or the pointer matches the patient ID. You're missing a negation there. Instead, use:

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

Here if Condition 1 ( patients_chart == NULL ) is true, then you do this:
patients_chart = patients_chart->next;

which is Null Pointer Dereferencing, thus causing Seg Fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM