c - 使用指针 : segmentation error 实现队列

标签 c pointers queue

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

#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 分配内存并立即使用它:

struct queue *Q; /* Where does Q point ? */

Q->front=Q->rear=NULL; /* Q not initialized, undefined behavior */

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

struct queue *Q;
Q = malloc(sizeof(*Q));
if (NULL == Q) {
    /* Tinfoil hat. */
}

关于c - 使用指针 : segmentation error 实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6579456/

相关文章:

c - C 中的静态库包含问题

c++ - 如何将二维 map 作为函数指针传递

c - 这段C代码的bug在哪里?

c++ - 为什么没有 boost::container::queue ?

delphi - 如何操作Collections.TQueue顺序?

c - 编译器在不同平台上实现C内联函数有什么区别吗

c - 将指针传递给具有指向 const 指针的形式参数的函数时的未定义行为?

c - 为什么netcat收不到第二个广播报文?

C++ 使用 *i 指针打开文件,在 Linux 中覆盖但在 Windows 中不覆盖

objective-c - 返回不兼容类型的变量