I am having difficulty locating a segmentation fault in a bit of code for a class project (this portion is ungraded). I am implementing a queue for an OS class and am having trouble with a segmentation fault in the add function.
void AddQueue(QElem * head, QElem * item) {
printf("WHERE\n");
if(head == NULL){
printf("THE\n");
head = item;
//item->next = item;
//item->prev = item;
}
else{
printf("$^&*\n");
(head->prev)->next = item;
printf("ARE\n");
item->prev = (head->prev);
printf("YOU\n");
item->next = head;
printf("FAILING\n");
head->prev = item;
}
printf("!?!?!?\n");
}
I have a Test function which I am calling from a different class...
void TestAddQueue()
{
printf("********************************************\n");
printf("Begin testing the add test function\n");
printf("********************************************\n");
QElem * queue;
InitQueue(queue);
for(int i = 0; i < 10; i++)
{
printf("Adding element %d\n", i+1);
QElem * newElem = NewItem();
printf("Changing payload value\n");
newElem->payload = i+100;
printf("Adding to the queue\n");
AddQueue(queue, newElem);
printf("Item added, payload value = %d\n", queue->payload);
printf("The previous payload = %d\n", queue->prev->payload);
}
for(int i = 0; i < 10; i++)
{
printf("Rotating list", i+1);
RotateQ(queue);
printf("Printing element %d\n", i+1);
printQElem(queue);
}
}
Here is the NewItem function...
QElem * NewItem()
{
// just return a new QElem struct pointer on the heap
QElem * newItem = calloc(1,sizeof(QElem));
newItem->next = newItem;
newItem->prev = newItem;
newItem->payload = -1;
return newItem;
}
...and here is the output of running the program...
********************************************
Begin testing the add test function
********************************************
Adding element 1
Changing payload value
Adding to the queue
WHERE
THE
!?!?!?
Segmentation fault
Now the head pointer which is passed into the add function should be NULL as it sent to an initializer function which just sets the value of the pointer to NULL, so I dont think this would cause my problem.
My guess is that following line is the one causing the issue...
printf("Item added, payload value = %d\n", queue->payload);
Probably when I attempt to get the payload value, either the struct I am attempting to access doesn't exist anymore or somehow the queue pointer got moved to an invalid space. Any feedback or nudges in the right direction would be appreciated.
Side Note: This is being compiled in a Unix server environment (bash) and at the moment I do not have access to an IDE to debug and view variables.