I'm new to C and have spent the past two days pulling my hair out over this issue. Everything in my code seems to line up with what I've researched, but I still keep getting a Segmentation Fault error. I have tried so hard to fix this but I can not spot what I'm doing wrong.
Here is my struct:
Code:
struct MovieType {
unsigned int id;
char movie_title[NAME_LENGTH];
int year;
};
typedef struct Node {
struct MovieType *data; //contains node item
struct Node *next;
struct Node *prev;
} NodeType;
struct ListType {
struct Node *head;
struct Node *tail;
int nextid;
};
And here is the function which gives me the error - it works up until the contents of if (currNode->next == NULL).
Code:
void addMovieToList(enum SortType s, struct ListType *list, struct MovieType *m) {
NodeType *newNode;
NodeType *currNode;
NodeType *prevNode;
currNode=list->head;
prevNode=NULL;
newNode=(NodeType *) malloc(sizeof(NodeType));
if (newNode == NULL) {
printf("mem allocation error");
exit(0);
}
newNode->data=m;
newNode->data->id=list->nextid;
if (currNode == NULL)
{
newNode->next = NULL;
newNode->prev = NULL;
list->head = newNode;
list->tail = newNode;
return;
}
if (currNode->next == NULL) {
list->head = newNode;
newNode->next = currNode;
newNode->prev = NULL;
currNode->prev = newNode;
return;
}
while (currNode->next != NULL)
{
list->head = newNode;
newNode->next = currNode;
newNode->prev = NULL;
currNode->prev = newNode;
return;
currNode = currNode->next;
}
currNode->next = newNode;
newNode->prev = currNode;
list->tail = newNode;
}
In my main function, I allocate memory for the lists, initialize the movie and then call this addMovieToList function. I can add the code for that here but the program seems to lie in the above function, as when I remove it everything works smoothly.
Any help would be appreciated.. Thank you.