Problem when trying to drop a stack in c

(it might be a stupid thing, but) I have a problem with the C implementation of the stack, when I try to clear it, the function to start the stack does an infinite loop. the top of the stack is never null. where am i making the mistake? Thank you!

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

      

+2


a source to share


2 answers


You are using free()

the same variable temp

every time in the loop, so who knows what will happen, you also need to update temp after you change top

, so update temp

inside your loop, like this:



void freeStack(ptr *top){

  while(*top!=NULL){
       ptr temp = *top;
      *top = temp->next;
      free(temp);
   }
  }

      

+4


a source


You are not incrementing the pointer temp

. You are missingtemp = temp->next



+3


a source







All Articles