diff --git a/lib/stack.c b/lib/stack.c index bb90a22..c8eb356 100644 --- a/lib/stack.c +++ b/lib/stack.c @@ -35,3 +35,16 @@ void *stack_pop(struct stack *stack) { stack->length = stack->length - 1; return data; } + +void stack_free(struct stack *stack) { + if (stack == NULL) { + exit(EXIT_FAILURE); + } + struct stack_node *node = stack->first; + while (node != NULL) { + struct stack_node *node_next = node->next; + free(node); + node = node_next; + } + free(stack); +} diff --git a/lib/stack.h b/lib/stack.h index 12f204b..bb61927 100644 --- a/lib/stack.h +++ b/lib/stack.h @@ -42,4 +42,10 @@ void stack_push(struct stack *stack, void *data); */ void *stack_pop(struct stack *stack); +/** + * @brief Frees the stack. + * @since v2.1.0 + */ +void stack_free(struct stack *stack); + #endif diff --git a/test/stack_test.c b/test/stack_test.c index 027bf68..3a0b2ab 100644 --- a/test/stack_test.c +++ b/test/stack_test.c @@ -10,6 +10,7 @@ void stack_initialization_test() { struct stack *stack = stack_initialization(); assert(stack->length == 0); assert(stack->first == NULL); + stack_free(stack); } void stack_push_test() { @@ -22,6 +23,7 @@ void stack_push_test() { assert(((uintptr_t)stack->first->next->data) == 8); assert(((uintptr_t)stack->first->next->next->data) == 4); assert(stack->first->next->next->next == NULL); + stack_free(stack); } void stack_pop_test() { @@ -35,4 +37,5 @@ void stack_pop_test() { assert(((uintptr_t)stack->first->data) == 8); assert(((uintptr_t)stack->first->next->data) == 4); assert(stack->first->next->next == NULL); + stack_free(stack); }