0

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!

derekerdmann
  • 17,696
  • 11
  • 76
  • 110
user3043594
  • 166
  • 10

2 Answers2

2

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");
}
creichen
  • 1,728
  • 9
  • 16
1
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.

0xF1
  • 6,046
  • 2
  • 27
  • 50
  • This was it! patients_chart = patientList; if (patients_chart != NULL) { while(patients_chart->id != patientID) { patients_chart = patients_chart->next; } } – user3043594 Nov 28 '13 at 16:03