problem when trying to empty a stack in c

Posted by frx08 on Stack Overflow See other posts from Stack Overflow or by frx08
Published on 2010-05-12T08:46:59Z Indexed on 2010/05/12 8:54 UTC
Read the original article Hit count: 422

Filed under:
|
|

Hi all, (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 empty 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;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about stack