Angargedon
Angargedon

Reputation: 73

Why does a segmentation fault appear with this data structure?

Given the datastructure

#define DATASTRUCTURE_H

#define MAXINDEX 307

typedef enum {So, Mo, Di, Mi, Do, Fr, Sa} eDayofTheWeek;

typedef struct{
    int Day;
    int Month;
    int Year;
    eDayofTheWeek WeekDay;
} sDate;

typedef struct{
    int Hour;
    int Minute;
    int Second;
}sTime;

typedef struct sALE{
    sDate Date;
    sTime Time;
    char *Description;
    char *Location;
    sTime Lenght;
    struct sALE *Next;
    struct sALE *Prev;
    int ID;
}sAppointment;

typedef struct sLE{
    sAppointment *Appointment;
    struct sLE *Next;
}sListEntry;

typedef struct{
    sListEntry *first;
    sListEntry *last;
}sHashEntry;

extern sHashEntry AppIndex[MAXINDEX];
extern sAppointment *First, *Last;

#endif

which will be used to create a appointment with sListElement in this function

sListEntry *Create = malloc(sizeof(sListEntry));
    if(Create != NULL){
        enter(1);
        printf("Termin erstellen");
        enter(2);
        if(getDate("Datum: ", &(Create->Appointment->Date))){
            if(getTime("Uhrzeit[Std:Min]: ", &(Create->Appointment->Time))){
                if(getDuration("Dauer[Std:Min:Sek]: ", &(Create->Appointment->Lenght))){
                    if(getText("Terminbeschreibung: ", 100, &(Create->Appointment->Description), 0)){
                        if(getText("Ort: ", 15, &(Create->Appointment->Location), 1))
                            check = 1;
                    }
                }
            }
        }

The segmentation fault happens when getDuration appears after I type an input:

int getDuration(char *prompt, sTime *time){
    char in[20];
    int Len;

    do{
        printf(prompt);
        scanf("%[^\n]", in);
        clearBuffer();
        Len = strlen(in);
    }while(!(getTimeFromStringLite(in, time)) && (Len != 0));

    return 1;
}

(getDuration asks the user for an input in hrs:min:sec format and adds it to the data structure, also allowing the user to make no input in there)

Why is that happening?

It worked back then when I did the same code but with the datatype sAppointment which is now included in sListEntry but since I changed the datatype and adapted the variables a segmentation fault appears. The variables are the only thing changed. Every other function stayed the same.

Upvotes: 0

Views: 58

Answers (1)

Angargedon
Angargedon

Reputation: 73

Quoting the comment: "doesn't look like youre allocating space for Create->Appointment, so as soon as you Create->Appointment-> you dereference an uninitialized pointer, invoking undefined behavior."

Upvotes: 1

Related Questions