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

动态扩容队列实现中resizeQueue函数的realloc内存分配错误排查求助

动态扩容队列实现中resizeQueue函数的realloc内存分配错误排查求助

我正在实现一个存储字符串的队列,用GDB调试时发现resizeQueue函数触发了内存分配错误,具体报错信息如下:

Program received signal SIGTRAP, Trace/breakpoint trap.
#13 0x00007ffd7348d235 in ucrtbase!_realloc_base () from C:\WINDOWS\System32\ucrtbase.dll
#14 0x00007ff7727c175b in resizeQueue (queue=0x5ffeb0) at queue.c:45

想请各位帮忙看看代码哪里出了问题,完整的队列实现和测试代码我都贴在下面了。

先提前说明一个我的设计逻辑:我知道当tail等于5时,数组并没有索引为5的位置,这是故意设计的——就是用这个条件触发扩容逻辑,而且这个越界的tail不会被解引用。不过我也不确定这个逻辑是不是真的没问题...调试时看起来是在分配第10个元素(索引9)的空间时失败的。

队列核心代码

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

typedef struct Queue {
    int tail; // 最后一个元素的下一个位置索引
    int head; // 第一个元素的索引
    int capacity;
    char** head_pt;
} Queue;

void allocQueue(Queue* queue) {
    assert(queue->capacity != 0);
    queue->head_pt = (char**)malloc(sizeof(char*) * queue->capacity);
    for (int i = 0; i < queue->capacity; i++) {
        queue->head_pt[i] = (char*)malloc(sizeof(char) * QUEUE_ELEM_SIZE);
        if (!queue->head_pt[i]) {
            printf("Queue Error: failed reallocating memory for a string");
            exit(1);
        }
    }
}

void resizeQueue(Queue* queue) {
    printf("RESIZE\n");
    queue->capacity *= 2;
    queue->head_pt = (char**) realloc(queue->head_pt, queue->capacity);
    if (!queue->head_pt) {
        printf("Queue Error: failed reallocating memory for head");
        exit(1);
    }

    for(int i = queue->tail; i < queue->capacity; i++) {
        queue->head_pt[i] = (char*)malloc(sizeof(char) * QUEUE_ELEM_SIZE);
        if (!queue->head_pt[i]) {
            printf("Queue Error: failed reallocating memory for a string");
            exit(1);
        }
    }
}

void enQueue(Queue* queue, char* data) {
    if (queue->head == -1 && queue->tail == -1) {
        queue->head = 0;
        queue->tail = 0;
    }

    if(queue->tail == queue->capacity) {
        resizeQueue(queue);
    }

    strcpy(queue->head_pt[queue->tail], data);
    queue->tail++;
}

测试代码

int main(void) {
    printf("------test Queue-----\n");
    Queue queue = {
        .capacity = 5,
        .tail = -1,
        .head = -1,
    };
    allocQueue(&queue);
    assert(queue.head_pt != NULL);
    printf("PASSED: allocating memory\n");

    char string [] = "a,b,c,d,e,f,g,h,i,j,k,";
    for (char* data = strtok(string, ","); data != NULL; data = strtok(NULL, ",") ) {
        enQueue(&queue, data);
        // printQueue(&queue);
    }

    return 0;
}

感谢各位能花时间看完我的问题,麻烦帮忙找找问题所在!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 03:10:39