I'm having issues solving this segmentation fault. I've been trying to fix this for a few hours, but I've run out of ideas+google searches, so I'm hoping to get some help.
What I have is a queue struct, which keeps track of head & tail nodes which are also structs.
The problem that I'm having is that any interaction with queue_1 is resulting in a segmentation fault.
typedef struct customer{
int id;
struct customer *next;
}customer_t;
typedef struct customer_queue{
customer_t *head;
customer_t *tail;
}queue;
queue *queue_1;
int main(){
initialize_queue(queue_1); //segmentation fault here.
customer_t *customer_1 = create_customer(1234); //this section works if we ignore the above line
}
void initialize_queue(queue *q){
q->head = NULL;
q->tail = NULL;
}
customer_t *create_customer(int id){
customer_t *customer = malloc(sizeof(customer_t));
customer->id = id;
customer->next = NULL;
return customer;
}
queue_1
is set to NULL when the program starts as it is an uninitialized variable at file scope. So when you pass it to initialize_queue
and subsequently try to set the fields you're dereferencing a NULL pointer. This is undefined behavior which in this particular situation causes your code to crash.
You don't need to define queue_1
as a pointer to a queue
. Just define it as a queue
and initialize it:
queue queue_1 = { NULL, NULL};
Strictly speaking you don't need to initialize it as both members will get implicitly initialized to NULL, but better to be explicit about it.
void initialize_queue(queue *q){
q = malloc(sizeof(queue));
q->head = NULL;
q->tail = NULL;
}
your queue is not allocated, to debug easily segmentation fault, use valgrind, it's a memory tracer, in complation add -g3 flag to get the line of the error on the execution, the execution : "valgring ./binary_name" and compilation: "gcc filename flags "-W -Wall .. -g""
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.