【发布时间】:2017-11-23 18:56:16
【问题描述】:
我厌倦了使用链表来实现堆栈,所以我将其作为全局实现,并创建了一些堆栈函数(push、pop、isempty) isempty 和 push 工作得很好, 但是我遇到了弹出功能的问题,基本上它可以工作,但我不知道为什么当我尝试释放我弹出的节点的内存时(保存数据后),它不工作并导致错误。 如果我只是删除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;
}
【问题讨论】:
-
struct stack* temp = (struct stack*)malloc(sizeof(struct stack*))-- 您正在分配指向堆栈的指针的大小,而不是堆栈本身的大小。同样不赞成投射malloc的结果。 -
struct stack *temp = malloc(sizeof *temp) -
"栈是全局的,所以 push 和 pop 都可以使用。"这是一个非常错误的理由来拥有一个全球性的。但话又说回来,没有任何充分的理由让它全球化。
-
您的
stack也确实是一个节点。只是说... -
我将
sizeof(struct stack*)更改为sizeof(struct stack)现在它的工作谢谢
标签: c linked-list free allocation