小编Pau*_*yen的帖子

C. Pop中的链接堆栈会导致分段错误,但Push不会!

我正在做一些简单的事情,所以希望这个问题很容易回答.我正在使用gcc进行编译.推动效果非常好.问题是流行音乐.每当我编译并运行它时,我都会遇到分段错误.

以下是pop和push功能:

int push(stack *stk, int data)
{
    stk->head = makeNode(data, stk->head);
    stk->length += 1;
    return data;
}

int pop(stack *stk)
{
    //Returns popped item
    //Returns -1 if stack length is zero
    if (stk->length < 1)
    {
        printf("No items to pop.");
        return -1;
    }
    int data = stk->head->value;
    struct node *toBeFreed = stk->head;
    stk->head = stk->head->ptr;
    free(toBeFreed);
    stk->length -= 1;
    return data;
}
Run Code Online (Sandbox Code Playgroud)

老实说,我不知道问题是什么,因为代码是相似的.我在push函数中重新分配堆栈中的head变量,但它会导致pop函数出错.对数据的分配也给了我一个seg错误.除了返回和堆栈长度赋值语句之外,几乎所有内容都会给出分段错误.你们任何人都可以帮我解决这个问题吗?造成这些seg故障的原因是什么?

这是整个计划:

#include <stdio.h>
#include <stdlib.h>
struct node 
{
    int value;
    struct node *ptr;
};

struct node …
Run Code Online (Sandbox Code Playgroud)

c

2
推荐指数
1
解决办法
1009
查看次数

标签 统计

c ×1