Reputation: 209
I was looking for simple stack implementation in C, and found something like 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 is empty.\n");
}
Probably it's newbie question but I'm not sure what exactly I'm freeing by free(temp). Seems like firstly I'm assigning current top to temp, then changing top to top->next(previous top is popped) and then deleting temp. Then what's the point of using temp?
Or maybe something is written wrong?
Upvotes: 0
Views: 88
Reputation: 178441
The reason to use temp
is because you need to remove the top of the stack (which you just popped), but you also want to modify the top to be the following element.
In order to do so, you need to store the old top somewhere, change the top, and then remove the last top.
The malloc()
is redundant and leaking memory, you do nothing with it, you bind it to temp
, but before using this variable, you rebind a different address to it.
As a rule of thumb that should hint you there is something wrong - why do you need a dynamic allocation in deletion? Though not always wrong, it does hint for investigating.
Upvotes: 3