C-堆栈实施,免费内存错误



我累了使用链接列表实现堆栈,所以我以全局的方式完成了堆栈,我做了一些堆栈函数(push,pop,isempty)Isempty和推动工作很棒,但是我在POP功能上遇到了问题,基本上它可以正常工作,但是当我尝试释放弹出的节点的内存(保存数据后)时,我不知道为什么它不起作用并导致错误。如果我只是删除POP函数中的" Free"行,它效果很好,但是您知道这里的问题,我必须在使用它之后释放堆存储器...那我该怎么办?

有一些代码:

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

struct stack
{
    int data;
    struct stack* next;
};
struct stack* top = NULL;  ///stack is global, so push and pop can use it.
int isEmpty()
{
    if (top == NULL)
        return 0;
    else return 1;
}
void push(int x)
{
    struct stack* temp = (struct stack*)malloc(sizeof(struct stack*));
    if (temp == NULL)
    {
        printf("Error! no allocation!!");
        return;
    }
    temp->data = x;
    temp->next = top;
    top = temp;
}
int pop()
{
    struct stack* temp;
    if (isEmpty() != 0)
    {
        temp = top;
        int x = top->data;
        top = top->next;
        free(temp);
        return x;
    }
    else
    {
        printf("stack is empty nothing to pop");
        return -1;
    }
}
int main()
{
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    push(6);
    push(7);
    int cur;
    while (isEmpty())
    {
        cur = pop();
        printf("|%d|--->", cur);
    }
    printf("n");
    return 0;
}

此纠正您的代码时,当您弹出ISEMPTY()是逆的,您会出现错误,而您在按下时分配了指针,而不是结构

为了澄清我的 isempty倒数

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

struct stack
{
    int data;
    struct stack* next;
};
struct stack* top = NULL;  ///stack is global, so push and pop can use it.
int isEmpty()
{
  return top == NULL;
}
void push(int x)
{
    struct stack* temp = malloc(sizeof(struct stack));
    if (temp == NULL)
    {
        printf("Error! no allocation!!");
        return;
    }
    temp->data = x;
    temp->next = top;
    top = temp;
}
int pop()
{
    struct stack* temp;
    if (!isEmpty())
    {
        temp = top;
        int x = top->data;
        top = top->next;
        free(temp);
        return x;
    }
    else
    {
        printf("stack is empty nothing to pop");
        return -1;
    }
}
int main()
{
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    push(6);
    push(7);
    int cur;
    while (!isEmpty())
    {
        cur = pop();
        printf("|%d|--->", cur);
    }
    printf("n");
    return 0;
}

最新更新