problem when trying to empty a stack in c
(probably it's a stupid thing but) I have a problem with a stack implementation in C language, when I try to empty it, the function to e开发者_StackOverflow中文版mpty the stack does an infinite loop.. the top of the stack is never null. where I commit an error? thanks bye!
#include <stdio.h>
#include <stdlib.h>
typedef struct stack{
size_t a;
struct stack *next;
} stackPos;
typedef stackPos *ptr;
void push(ptr *top, size_t a){
ptr temp;
temp = malloc(sizeof(stackPos));
temp->a = a;
temp->next = *top;
*top = temp;
}
void freeStack(ptr *top){
ptr temp = *top;
while(*top!=NULL){
//the program does an infinite loop
*top = temp->next;
free(temp);
}
}
int main(){
ptr top = NULL;
push(&top, 4);
push(&top, 8);
//down here the problem
freeStack(&top);
return 0;
}
You're free()
ing the same temp
variable every time in the loop, so who knows what'll happen, you also need to update temp after you've changed top
, so update temp
inside your loop e.g. like so:
void freeStack(ptr *top){
while(*top!=NULL){
ptr temp = *top;
*top = temp->next;
free(temp);
}
}
You are not incrementing temp
pointer. You are missing temp = temp->next
精彩评论