So, I am implementing a linked-list based queue and I put the node information in a structure and I put the head and the tail of the queue in a structure. When I try to add a node, I have to use -> twice, and I ended up getting a segmentation fault error.
Now my code is part of a larger program with user input and multiple options and stuff but I simplified it down for ease.
typedef enum statucEnum {CALLED_AHEAD, WAITING} status;
typedef struct nodeStruct{
char* name;
int groupSize;
status inStatus;//in resturant status
struct nodeStruct* next;
}Node;
//structure to encapsulate the head of the queue along with the tail
typedef struct headStruct{
Node* head;
Node* tail;
}Queue;
void intializeQueue(Queue* queue){
queue->head = NULL;
queue->tail = NULL;
}
int main(){
Queue queue;
intializeQueue(&queue);
//program ask what the user wants to do, and it decides to add to the queue
doAdd(&queue);
}
void doAdd(Queue* queue){
//usually the program would ask the user to input a age and name
int age = 4;
name = "v";
Node* newNode;
newNode = malloc(sizeof(Node));
newNode->groupSize = size;
newNode->name = name;
newNode->inStatus = WAITING;
addToList(queue, newNode);
}
When I use valgrind, it tells me that the segmentation fault is in this code segment
void addToList(Queue* queue, Node* node){
printf("Address of parameter: %p", node);
if (queue->head == NULL){
queue->head->next = node; \\this is where the error occurs
queue->tail->next = node;
}else{
queue->tail->next = node;
queue->tail = node;
}
}
More specifically at the line of queue->head->next = node
I can't seem to figure out what I am doing wrong.
When you head is NULL then how can you set queue->head->next = node;. First of all set you head value then you can update your head next point. So see following code
void addToList(Queue* queue, Node* node){
printf("Address of parameter: %p", node);
if (queue->head == NULL){
queue->head = node; \\this is where the error occurs
queue->tail = node;
}else{
queue->tail->next = node;
queue->tail = node;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments