I have the following function that adds a node to the front of a doubly-linked linked list.
Code:
#define HEAD list->head
#define TAIL list->head->prev
...
void add_front(llist* list, lnode* node)
{
printf("function has been run! \n");
/* new head needs to point to old head as its next.
* new head needs to point to old tail as its prev.
* tail needs to point to new head as its next.
* old head needs to point to new head as its prev.
* llist needs to recognize new head as head.
*/
/* If the list is not empty */
if(HEAD != NULL) {
printf("condition is being checked! \n");
/* if the list contains more than 1 element */
if(HEAD->next != NULL){
node->next = HEAD;
node->prev = TAIL;
TAIL->next = node;
HEAD->prev = node;
}
}
list->head = node;
}
Pretty sure the HEAD and TAIL are being used correctly.
The function is being used as follows:
Code:
llist myList;
lnode myNode;
lnode skippy;
int main()
{
myNode.x = 5;
myNode.y = 7;
skippy.x = 1;
skippy.y = 9;
myList.head = &myNode;
add_front(&myList, &skippy);
printf("myNode.x= %d\n", myNode.x);
printf("skippy.x= %d\n", skippy.x);
printf("testing add_front... \n");
printf("skippy.y= %d\n", myNode.next->y);
return 0;
}
To give some background on the structs, they are defined in a header file as:
Code:
/* The node struct. Has a prev pointer, next pointer, and data. */
typedef struct _lnode {
struct _lnode *prev;
struct _lnode *next;
int x;
int y;
} lnode;
/* The linked list struct. Has a head pointer. */
typedef struct _llist {
lnode *head;
} llist;
when I run the test case, I get the following output:
Code:
function has been run!
condition is being checked!
myNode.x= 5
skippy.x= 1
testing add_front...
Segmentation fault
Any ideas? I know this is a lot of code to look through, and I greatly appreciate any help received.