I have to implement the pop method of a stack in C and I have done the following:
Stack_pop(tStack *stack) {
if (stack != NULL)
{
tStackNode *node = malloc(sizeof(tStackNode));
node=stack->first->next;
stack = node;
}
else
{
return -1;
}
}
In theory it should work: I first get the node corresponding to the next one and then assign it as the current node. But when I try it, it hangs, so it's a memory allocation error. The tStack struct is as follows:
typedef struct tNode {
tValue e;
struct tNode *next;
} tStackNode;
The problem lies here:
That code has 3 flaws:
That memory reservation with
malloc
is unnecessary, the only thing it causes is a memory leak .The expression:
stack->first->next
will return the memory address of the next node but then store it in the pointernode
, it doesn't make any sense to do that, since the pointernode
will be freed in memory when the function is finished (so you lose the reference).Finally, you save the content of
node
, instack
, that is, at no time do you update the pointerfirst
(the member of thetStackNode
) structure.Solution:
As you will see, we need to rely on a helper pointer to be able to free the last node and additionally to that, update the pointer/member
first
. Since you must take into account that itfirst
must have the base address of the following node.