我的C语言queue_poll函数有什么错误?

问题描述 投票:0回答:2

我目前正在尝试实现一个队列轮询函数,该函数轮询队列中的最后一个元素。我实在不明白为什么这个功能不起作用。该函数背后的逻辑应该非常简单,但看起来并非如此。我很想知道为什么我不能使用这样的指针。

void *queue_poll(queue_object *queue) {
    if (queue == NULL) {
        return NULL;
    }
    queue_object *prev = queue;
    while (prev->next != NULL) {
        queue_object *tmp = prev->next;
        prev = tmp;
    }
    void *object = prev->object;
    free(prev);
    return object;
}

我尝试打印这些值来调试问题,但没有任何反应。我真的被困在这里了。我将不胜感激任何帮助。

void main(void) {

    char *A = malloc(sizeof(char));
    char *B = malloc(sizeof(char));
    char *C = malloc(sizeof(char));
    char *D = malloc(sizeof(char));
    char *E = malloc(sizeof(char));
    char *F = malloc(sizeof(char));

    *A = 'A';
    *B = 'B';
    *C = 'C';
    *D = 'D';
    *E = 'E';
    *F = 'F';

    FCFS_startup();

    queue_add(A, FCFS_queue);
    queue_add(B, FCFS_queue);
    queue_add(C, FCFS_queue);
    queue_add(D, FCFS_queue);
    queue_add(E, FCFS_queue);
    queue_add(F, FCFS_queue);

    void *value = queue_poll(FCFS_queue);

    printf("%c\n", *(char*)value);
}

提前谢谢您。

亲切的问候。

我尝试使用

prev != NULL
代替
prev->next != NULL
但仍然没有打印任何内容。

arrays c linked-list queue clion
2个回答
0
投票

您很可能在调用

free(prev);
后遇到分段错误。由于
prev
是在堆栈上分配的,因此不需要释放它。


0
投票

void *queue_poll(queue_object *queue) { if (队列 == NULL || 队列->下一个 == NULL) { 返回空值; // 处理空队列 }

queue_object *prev = queue;
queue_object *curr = queue->next;

// Find the last node
while (curr->next != NULL) {
    prev = curr;
    curr = curr->next;
}

// Detach the last node
prev->next = NULL;

void *object = curr->object;
free(curr);
return object;

}

使用此代码希望它有效!

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.