0
#include <stdio.h>
#include <malloc.h>

struct node
{
    int data;
    struct node *next;
};

struct queue
{
    struct node *front;
    struct node *rear;
};

struct queue *q;

void create_queue(struct queue *);
int main()
{
    create_queue(q);

    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->data = 42;

    q->front = ptr; <-- here it fails with Sementaion fault

    return 0;
}

void create_queue(struct queue *q)
{
    q = (struct queue*)malloc(sizeof(struct queue));
    q->rear = NULL;
    q->front = NULL;
}

And this fails on trying to assign ptr to queue front, but if i move the line q = (struct queue*)malloc(sizeof(struct queue)); to the main function before create_queue(q) everything works well. What the reason the Segmentation fault error depends on the memory allocation position in the code.

klutt
  • 30,332
  • 17
  • 55
  • 95
Dmitrii
  • 604
  • 2
  • 9
  • 30

2 Answers2

2

You need to pass a double pointer struct queue **q to create_queue()

void create_queue(struct queue **q)
{
    *q = (struct queue*)malloc(sizeof(struct queue));
    (*q)->rear = NULL;
    (*q)->front = NULL;
}

This is because you want to update the pointer q itself, not what it points to.

th33lf
  • 2,177
  • 11
  • 15
1

following function does not update global variable q.

void create_queue(struct queue *q)
{
    q = (struct queue*)malloc(sizeof(struct queue));
    q->rear = NULL;
    q->front = NULL;
}

It is in fact working with local variable which goes out of scope with subsequent memory leak (and global variable still pointing to some garbage). you need to define your function this way:

void create_queue(struct queue **q)
{
    *q = (struct queue*)malloc(sizeof(struct queue));
    *q->rear = NULL;
    *q->front = NULL;
}

and call it

create_queue(&q);

so you should pass address of your variable into the function instead of value.

Maxim Sagaydachny
  • 2,098
  • 3
  • 11
  • 22