C - 堆栈工具,可用内存错误

时间:2017-11-23 18:56:16

标签: c linked-list free allocation

我厌倦了使用链表实现堆栈,所以我做了全局,我做了一些堆栈功能(push,pop,isempty) isempty和推动工作很棒, 但我有pop功能的问题,基本上它工作,但我不知道为什么当我试图释放我poped节点的内存(保存数据后),它不工作,并导致错误。 如果我只是删除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;
}

1 个答案:

答案 0 :(得分:1)

这是你的代码纠正了当你弹出你的isempty()是反向的时你有一个错误,当你按

时你分配了指针而不是你的结构

为了澄清我反转你的isempty,当它为空时返回0(假)是不合逻辑的

#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;
}