I am fairly new to using pointers and queues and such, but this is a program we're required to write for class and I finally got it to compile completely without any errors or warnings and now I go to run it with a.out and all I get is the message in the title of this post: "segmentation fault (core dumped)". does anyone know what this means or how to fix it? My code is below. I also included my Makefile because I don't have a lot of experience with those either and thought maybe that was the problem. Thanks in advance for any help!
this is my queue.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include "boolean.h"
#include "queue.h"
int menu(void);
int main(void){
queue q;
int selection, data;
boolean quit=FALSE;
init_queue(&q);
while(!quit){
scanf("%d", &selection);
switch(selection){
case 1:
if(is_full()){
printf("The queue is full\n");
}
else{
printf("Please enter a number to add to the queue.\n");
scanf("%d", &data);
add(&q, data);
}
break;
case 2:
if (is_empty(q)){
printf("The queue is already empty\n");
}
else{
data = fetch(&q);
printf("%d was removed\n\n", data);
}
break;
case 3:
print_queue(q);
break;
case 4:
quit=TRUE;
default:
printf("Sorry, but that is not a valid selection.\n\n");
break;
}
if(!quit) menu();
}
}
int menu(void){
printf("1. Add\n"); printf("2. Fetch\n"); printf("3. List\n"); printf("4. Quit\n"); printf("Enter a selection: ");
}
This is my queue.h
Code:
#include <stdio.h>
#include "boolean.h"
#include <stdlib.h>
typedef struct queuenode{
int data; struct queuenode *next;
} *node_pointer;
typedef struct endpoint{
node_pointer front;
node_pointer back;
}*queue;
void init_queue(queue *);
boolean is_full(void);
boolean is_empty(queue);
void add(queue *, int);
int fetch (queue *);
void print_queue(queue);
void init_queue(queue *q){
(*q) -> front = NULL;
(*q) -> back = NULL;
}
boolean is_full (void){
node_pointer temp;
temp = (node_pointer) malloc(sizeof(struct queuenode));
if (temp == NULL){
return TRUE;
}
else{
free(temp);
return FALSE;
}
}
boolean is_empty(queue q){
if ((q -> front == NULL) && ((q -> back == NULL)))
return TRUE;
else
return FALSE;
}
void add(queue *q, int add){
queue queue;
queue = *q;
node_pointer temp;
temp = (node_pointer) malloc(sizeof(struct queuenode));
temp -> data = add;
temp -> next = NULL;
if (is_empty(queue)){
(*q) -> front = temp;
(*q) -> back = temp;
}
else{
(*q) -> back -> next;
(*q) -> back = temp;
}
}
int fetch (queue *q){
node_pointer temp;
int fetch_data;
temp = (*q) -> front;
fetch_data = temp -> data;
if (((*q) -> front) == ((*q) -> back)){
(*q) -> front = NULL;
(*q) -> back = NULL;
}
else{
(*q) -> front -> next;
free(temp); return fetch_data;
}
}
void print_queue (queue q){
node_pointer temp;
temp = q -> front;
while (temp!=NULL){
printf("%d\n", (temp -> data));
temp = temp -> next;
}
and this is my make file
Code:
CC = gcc
CFLAGS = -o a.out
LDFLAGS = -lm
OBJS = queue.o
a.out: $(OBJS)
$(CC) $(CFLAGS) $(OBJS) $(LDFLAGS)
clean:
rm $(OBJS) a.out
print: enscript -Plab01 *.c *.h typescript