c - Simple stack, pop -
i looking simple stack implementation in c, , found that:
void pop(struct stack **top) { struct stack *temp; temp = malloc(sizeof(struct stack)); if(*top != null) { printf("%d popped.\n",(*top)->data); temp = (*top); (*top) = (*top)->prev; free(temp); } else printf("stack empty.\n"); }
probably it's newbie question i'm not sure i'm freeing free(temp). seems firstly i'm assigning current top temp, changing top top->next(previous top popped) , deleting temp. what's point of using temp?
or maybe written wrong?
the reason use temp
because need remove top of stack (which popped), want modify top following element.
in order so, need store old top somewhere, change top, , remove last top.
the malloc()
redundant , leaking memory, nothing it, bind temp
, before using variable, rebind different address it.
as rule of thumb should hint there wrong - why need dynamic allocation in deletion? though not wrong, hint investigating.
Comments
Post a Comment