I am kind of new to c and tried to use a single linked list for stack implementation. To implement push() and pop() functions I passed a double pointer. In main I initialize Node *node_head to NULL
I use malloc() and free() to successfully handle memory leaks but it seems that I have memory leaks somewhere that I can't figure out. Should I take a different approach when freeing a double pointer? Thank you and here are the two functions:
void stack_push(Node **node_head, int d)
{
Node *node_new = malloc(sizeof(Node));
node_new -> data = d;
node_new -> next = *node_head;
*node_head = node_new;
}
int stack_pop(Node **node_head)
{
Node *node_togo = *node_head;
int d = 0;
if(node_head)
{
d = node_togo -> data;
*node_head = node_togo -> next;
free(node_togo);
}
return d;
}
The only error in your code is in function stack_pop.
if(node_head)
Of course you may check whether node_head is equal to NULL though in my opinion it is a superflouos check. But you have to check that *node_head
is not equal to NULL.
The function could look like
int stack_pop(Node **node_head)
{
int d = 0;
if( *node_head )
{
Node *node_togo = *node_head;
d = node_togo -> data;
*node_head = node_togo -> next;
free( node_togo );
}
return d;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.