Explain to me, please, this moment: When you call the function again, the variable new is located exactly at the same address as S->top .

Why does this work and how to do it right?

 struct list{ int val; struct list *prev; }; struct stack{ unsigned len; struct list *top; }; void push(struct stack *S, int val){ struct list new; new.val = val; if (S->len == 0){ new.prev = NULL; } else{ new.prev = S->top; }; S->top = &new; S->len += 1; } 
  • four
    This is how memory allocation in the stack works, this is normal. Your problem is that new ceases to exist as soon as you exit push() . Use struct list *new = malloc(sizeof(struct list)); and then the structure will exist even after exiting the function. - HolyBlackCat
  • Thank you very much, I overlooked this fact. - doktor-zlo

0