VSCode 中的分段错误,但在 REPL ( C ) 上运行良好

问题描述

以下是使用堆栈反转队列的函数代码。不知道我哪里出错了:

void reverse(Queue *q)
{
    int temp1,temp2;
    Stack *s1 = malloc(sizeof(Stack));
    removeAllItems(&(s1->ll));
    while(((q->ll).size)!=0)
    {
        temp1 =  (((q->ll).head)->item);
        push(s1,temp1);
        dequeue(q);
    }
    while(((s1->ll).size)!=0)
    {
        temp2 = (((s1->ll).head)->item);
        enqueue(q,temp2 );
        pop(s1);
    }
}

解决方法

Stack *s1 = malloc(sizeof(Stack));

正在分配一些未初始化的内存。在某些情况下,malloc 会失败并返回 NULL。在其他情况下,它将重用一些以前的 free-d 区域。

你可能想要malloc

if (s1 == NULL) { perror("malloc Stack"); exit(EXIT_FAILURE); };
memset (s1,sizeof(Stack));

检查 malloc 是否失败并正确清除内存区域。

removeAllItems(&(s1->ll));

正在访问一些未初始化的字段,其中可能包含垃圾数据。

阅读现代 C 和 C 编译器的文档。如果您使用 GCC,请使用所有警告和调试信息进行编译:{{1​​}}

然后使用像 GDB 这样的调试器。

考虑使用 Clang static analyzerFrama-C 等工具,或者编写自己的 GCC plugin,或者使用 valgrind