Segmentation fault!!??

U

uniquerockrz

Guest
A rather simple program that represents working of a queue
Code:
/* Queue */
#include<stdio.h>
#define MAX 10
typedef struct{
	int q[MAX];
	int front,rear;
}queue;
int main(){
	int flushqueue(queue *,int);
	int isfull();
	int isempty();
	int enqueue(queue *,int);
	int dequeue(queue *);
	int printqueue(queue);
	queue que;
	que.front=que.rear=-1;
	int a,choice,item;
	a=flushqueue(&que,-1);
	while(choice!=4){
		printf("\n\n\n\t*** Queue ***\n");
		printf("1. Enqueue\n2. Dequeue\n3. Display queue\n4. Exit");
		printf("\nEnter choice : ");
		scanf("%d",&choice);
		switch(choice){
			case 1: 
				if(isfull(que))
					printf("Queue Full!");
				else{
					printf("Enter number to be added : ");
					scanf("%d",&item);
					a=enqueue(&que,item);
					if(a==0){
						printf("Number added sucessfully!\n");
						a=printqueue(que);
					}
				}
				break;
			case 2:
				if(isempty(que))
					printf("Queue Empty!");
				else{
					printf("%d deleted sucessfully!",dequeue(&que));
					printqueue(que);
				}
				break;
			case 3:
				a=printqueue(que);
				break;
			}
	}
	return 0;
}
int isfull(queue que){
	if(que.front==0 && que.rear==MAX-1)
		return 1;
	else
		return 0;
}
int isempty(queue que){
	if(que.front==-1)
		return 1;
	else
		return 0;
}
int enqueue(queue *que,int v){
	int i,a;
	if(que->front==-1)
		que->front=que->rear=0;
	else if(que->rear=MAX-1){
		for(i=que->front;i<que->rear;i++){
			que->q[i-que->front]=que->q[i];
			a=flushqueue(&que,i);
		}
		que->rear=que->rear-que->front+1;
		que->front=0;
	}
	else
		que->rear++;
	que->q[que->rear]=v;
	return 0;
}
int dequeue(queue *que){
	int t,a;
	t=que->q[que->front];
	a=flushqueue(que->front);
	if(que->front==que->rear)
		que->front=que->rear=-1;
	else
		que->front++;
	return t;
}
int printqueue(queue que){
	int i;
	for(i=0;i<MAX;i++)
		printf("%d  ",que.q[i]);
	return 0;
}
int flushqueue(queue *que,int s){
	int i;
	if(s==-1){
		for(i=0;i<MAX;i++)
			que->q[i]=0;
	}
	else
		que->q[s]=0;
	return 0;
}

But when I compile and run the code, I get an error while adding an entry the second time. Terminal output below:

Code:
[srvmdk@localhost Rough]$ gcc Queue.c
[srvmdk@localhost Rough]$ ./a.out



	*** Queue ***
1. Enqueue
2. Dequeue
3. Display queue
4. Exit
Enter choice : 1
Enter number to be added : 10
Number added sucessfully!
10  0  0  0  0  0  0  0  0  0  


	*** Queue ***
1. Enqueue
2. Dequeue
3. Display queue
4. Exit
Enter choice : 1
Enter number to be added : 12
Segmentation fault (core dumped)
[srvmdk@localhost Rough]$

Any ideas why and any solution how to avoid it? Thanks in advance.:mrgreen:
 

gk2k

gkbhat.blogspot.com
If you still have not got the error this is the line
Code:
else if(que->rear=MAX-1){

If you encounter segmentation fault use
Code:
 gdb ./a.out
when you get segmentation fault use
Code:
 bt
to get the backtrace of function call
 
Top Bottom