I'm trying to create an abstract data type HiddenHeaders and accompanying functions (IsEmpty and Enqueue) whose low-level structure would be transparent to the user writing main(). Initialization of HiddenHeaders *my_list actually creates a linked list struct listStructure, but the user should not be aware of it - they would only interact with struct listStructure by variables of HiddenHeaders type and any changes in the functions or in the underlying linked list wouldn't require any changes in main(). But my program keeps exiting with SIGSEGV, segmentation fault, as soon as functions are called. Why is that?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct listStructure {
int data;
struct listStructure *nextPtr;
};
typedef struct listStructure ListStructure;
struct hiddenHeaders {
ListStructure *ptr_to_list;
};
typedef struct hiddenHeaders HiddenHeaders ;
HiddenHeaders * Enqueue (HiddenHeaders *abstract, int user_input);
bool IsEmpty (HiddenHeaders *abstract);
int main () {
HiddenHeaders *my_list;
int input;
my_list = NULL;
printf ("Enter data item value to add ");
scanf ("%d", &input);
my_list = Enqueue (my_list, input);
return 0;
}
bool IsEmpty(HiddenHeaders *abstract) {
ListStructure *adt_el = abstract->ptr_to_list;
bool isEmpty;
if (adt_el == NULL) {
return isEmpty=true; }
else
return isEmpty=false;
}
HiddenHeaders * Enqueue (HiddenHeaders *abstract, int user_input) {
ListStructure *adt_el = abstract->ptr_to_list;
HiddenHeaders *abstract_Ptr = abstract;
if (!IsEmpty(abstract)) {
while ((adt_el -> nextPtr) == NULL) {
adt_el = adt_el -> nextPtr; }
adt_el -> nextPtr = (ListStructure *) malloc (sizeof (ListStructure));
adt_el = adt_el -> nextPtr;
adt_el -> nextPtr = NULL;
adt_el -> data = user_input;
return abstract_Ptr;
}
else {
adt_el = (ListStructure *) malloc (sizeof (ListStructure));
adt_el -> nextPtr = NULL;
adt_el -> data = user_input;
return abstract;
}
}
The way I attempted to implement this is by first creating a linked list struct, defining it as a new type (ListStructure), then creating a new struct that contains a pointer to a previously defined linked list, and finally defining this new struct as a type (HiddenHeaders). The functions accept arguments of the HiddenHeaders type but in the function body, this argument is unwrapped to ListStructure and then operations are performed on the contents of this underlying linked list (or whatever other structure it would be).
my_listis a null pointer andEnqueueexpects a non-null pointer as its first argument.