You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义循环队列使用循环触发段错误,请求排查代码问题

循环队列段错误问题排查

你的代码触发段错误以及逻辑异常的核心问题如下:

  • 野指针访问:main函数中queue *root;仅声明指针但未分配内存或指向有效队列对象,直接传给createqueue会导致对未知内存地址的写入,这是触发段错误的首要原因。
  • 入队逻辑顺序错误:第一个节点插入时,先执行q->tail->next = q->head;(此时q->head为NULL),之后才将q->head指向新节点,导致循环链表的闭环未正确建立。
  • 队列空状态处理缺失:dequeue函数未处理队列只剩最后一个节点的情况,出队后会出现head为NULL但tail仍指向旧节点的不一致状态,后续操作会引发错误。
  • 函数返回值缺失:display函数声明为int类型,但函数末尾无return语句,会导致未定义行为。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *next;
};
typedef struct node node;

typedef struct{
    node *head;
    node *tail;
} queue;

void createqueue(queue *q){
    q->head = NULL;
    q->tail = NULL;
}

int enqueue(queue *q, int value){
    node *newnode = malloc(sizeof(node));
    if (newnode == NULL) return 0;
    
    newnode->data = value;
    newnode->next = NULL;
    
    if (q->head == NULL) {
        // 处理第一个节点,head和tail都指向它,同时形成闭环
        q->head = newnode;
        q->tail = newnode;
        newnode->next = q->head;
    } else {
        // 已有节点时,插入到tail后,更新tail并重新闭环
        q->tail->next = newnode;
        q->tail = newnode;
        q->tail->next = q->head;
    }
    return 1;
}

int dequeue(queue *q){
    if (q->head == NULL) return 0;
    
    if (q->head == q->tail) {
        // 队列只剩一个节点,出队后清空队列
        free(q->head);
        q->head = NULL;
        q->tail = NULL;
    } else {
        node *temp = q->head;
        q->head = q->head->next;
        q->tail->next = q->head;
        free(temp); // 释放内存,避免内存泄漏
    }
    return 1;
}

int display(queue *q){
    if (q->head == NULL) return 0;
    
    node *printval = q->head;
    printf("\n");
    do {
        printf("%d-->", printval->data);
        printval = printval->next;
    } while (printval != q->head);
    printf("\b\b\b   \n"); // 去除末尾多余的"-->"
    return 1;
}

int main(){
    queue root; // 直接声明队列对象,避免野指针
    createqueue(&root);
    
    printf("Enter the size of the queue: ");
    int size;
    scanf("%d", &size);
    
    for(int i=0; i<size; i++){
        int value;
        printf("Enter the value of the %d element: ", i);
        scanf("%d", &value);
        enqueue(&root, value);
    }
    
    display(&root);
    
    return 0;
}

关键修正说明

  1. 修复野指针:main函数中直接声明queue root,通过&root传递给操作函数,避免未初始化指针的非法访问。
  2. 调整入队逻辑:优先判断队列是否为空,处理第一个节点时直接建立闭环,确保循环链表结构正确。
  3. 完善出队逻辑:处理队列仅剩一个节点的情况,清空head和tail避免状态不一致;同时添加内存释放操作,防止内存泄漏。
  4. 补充返回值:给display函数添加return语句,修正未定义行为;额外优化输出格式,去除末尾多余的箭头。

内容的提问来源于stack exchange,提问作者Harshit Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:33:10