acidlategamer acidlategamer -4 years ago 97
C Question

Why this program gives segmention fault in this queue program

This is the C program for queue. I have just written it for insert values. The problem I am getting is I get segmentation fault whenever I insert the first element.

#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 *);
struct queue *insert(struct queue *,int);

int main()
{

int val, option;
create_queue(q);

do
{

printf("\n *****MAIN MENU*****");
printf("\n 1. INSERT");
printf("\n Enter your option : ");
scanf("%d", &option);

switch(option)
{
case 1:
printf("\n Enter the number to insert in the queue:");
scanf("%d", &val);
q = insert(q,val);
break;

}

}while(option != 5);

return 0;
}

void create_queue(struct queue *q)
{
q = (struct queue *)malloc(sizeof(struct queue));
q->rear = NULL;//how this happened without any error??
q->front = NULL;
}

struct queue *insert(struct queue *q,int val)
{

struct node *ptr;

ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("error in allocating\n");
return -1;
}
ptr->data = val;
if(q->front == NULL)
{
q->front = ptr;//here I get segmentation fault
q->rear = ptr;
q->front->next = q->rear->next = NULL;
}
else
{
q->rear->next = ptr;
q->rear = ptr;
q->rear->next = NULL;
}

return q;
}


what is wrong with my program?
Why the assignment of a new node does not work, what is the current syntax?

Answer Source

The problem here is, while you call functions with the global variable and accept that in a function parameter, the function parameter becomes local to the called function.

This way, the local variable shadows the global variable and since C uses pass-by-value for function argument passing, any changes made to the local copy is not reflected to the caller, anyway.

Finally, the global pointer p remains uninitialized. Attempt to dereference that causes undefined behavior.

You either

  • don't need to pass the global(s) as parameter
  • pass the address of the pointer and operate on the same inside the function.

That said, please see this discussion on why not to cast the return value of malloc() and family in C..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download