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

Pau*_*yen 2 c

我正在做一些简单的事情,所以希望这个问题很容易回答.我正在使用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 *makeNode(int value, struct node *ptr)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->value = value;
    newNode->ptr = ptr;
    return ptr;
}

typedef struct stack
{
    struct node *head;
    int length;
} stack;

stack makeStack()
{
    stack stk;
    stk.head=NULL;
    stk.length = 0;
    return stk;
}

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

int pop(stack *stk)
{
    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;
}

int main()
{
    stack s = makeStack();
    printf("Pushing ints one through five. Should display ints one through five on separate lines: \n");
    int i;
    for (i = 1; i <= 5; i++)
            printf("%d\n",push(&s, i));
    printf("Popping ten values. Should display ints one through five in reverse order on separate lines along with 5 error statements.\n");
    for (i = 0; i <= 10; i++)
            printf("%d\n",pop(&s));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 8

struct node *makeNode(int value, struct node *ptr)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->value = value;
    newNode->ptr = ptr;
    return ptr;
}
Run Code Online (Sandbox Code Playgroud)

你想回来newNode,而不是ptr.

你得到段错误的原因是,由于makeNode错误堆栈将保持为空,但是size将增至5,所以当你pop的栈不知道这是空的,它试图取消引用空指针.