使用指针实现队列:分段错误 [英] Implementation of Queue using pointers : segmentation error

查看:62
本文介绍了使用指针实现队列:分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施 FIFO.代码编译没有错误,但我在运行程序时遇到 segmentation fault.有什么问题?

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;
}

推荐答案

您没有为 Q 分配内存并立即使用它:

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 */

所以 Q 指向堆栈上的某个随机值.要解决它,请使用 malloc:

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. */
}

这篇关于使用指针实现队列:分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆