问题
I am trying to implement a FIFO. The code compiles without errors but i get segmentation fault
when running the program. What is the problem?
#include <stdio.h>
#include <stdlib.h>
struct cell
{
int element;
struct cell *next;
};
struct queue
{
struct cell *front;
struct cell *rear;
};
void enqueue(int x, struct queue *Q);
void dequeue(struct queue *Q);
main()
/* Manipulation of a linked queue of cells. */
{
struct queue *Q;
struct cell *q;
int i;
Q->front=Q->rear=NULL;
for(i=0; i<8; i++) {enqueue(i+1, Q);}
printf("Q->front = %p, Q->rear = %p\n", Q->front, Q->rear);
q=Q->front;
while(q!=NULL)
{
printf("cell = %d, %p\n", q->element, q->next);
q=q->next;
}
for(i=0; i<10; i++) dequeue(Q);
printf("Q->front = %p, Q->rear = %p\n", Q->front, Q->rear);
q=Q->front;
while(q!=NULL)
{
printf("cell = %d, %p\n", q->element, q->next);
q=q->next;
}
return(0);
}
void enqueue(int x, struct queue *Q)
{
struct cell *p;
p=(struct cell *)malloc(sizeof(struct cell));
if(Q->rear != NULL) Q->rear->next = p;
Q->rear = p;
if(Q->front == NULL) Q->front = p;
Q->rear->element = x; Q->rear->next = NULL;
return;
}
void dequeue(struct queue *Q)
{
struct cell *q;
if(Q->front == NULL) {printf("Error: Queue is empty.\n"); exit(1);}
else {q=Q->front; Q->front = Q->front->next; free(q);}
if(Q->front == NULL) Q->rear = NULL;
return;
}
回答1:
You are not allocating memory for Q
and using it right away:
struct queue *Q; /* Where does Q point ? */
Q->front=Q->rear=NULL; /* Q not initialized, undefined behavior */
So Q points to some random value on the stack. To solve it, use malloc
:
struct queue *Q;
Q = malloc(sizeof(*Q));
if (NULL == Q) {
/* Tinfoil hat. */
}
回答2:
You have no space allocated to your struct queue *Q;
struct queue *Q;
struct cell *q;
int i;
Q->front=Q->rear=NULL;
Q
is just an uninitialized pointer. It doesn't point to anything valid, so you can't dereference it as you do in Q->front=Q->rear=NULL;
Change it to allocate Q on the stack, and pass its address to your functions.
struct queue Q;
struct cell *q;
int i;
Q.front=Q.rear=NULL;
for(i=0; i<8; i++) {enqueue(i+1, &Q);}
来源:https://stackoverflow.com/questions/6579456/implementation-of-queue-using-pointers-segmentation-error