diff --git a/stack.c b/stack.c index 4137848141ec5250cf640707995a2ac8a6c13c0f..1d8d39ba8fa46b0c5a67709b43e8ee9f2053efa0 100644 --- a/stack.c +++ b/stack.c @@ -7,7 +7,9 @@ #include <stdio.h> void stack_init(stack *s, int size) { - + s->data = malloc(size * sizeof(int)); + s->size = size; + s->top = -1; } bool stack_is_empty(stack s) { @@ -29,5 +31,8 @@ void stack_peek(stack s, int *val) { } void stack_destroy(stack *s) { - + free(s->data); + s->data = NULL; + s->top = -1; + s->size = -1; } diff --git a/test.c b/test.c index ae29034566f2481d6db64696c74a15d0fc93a6bf..380eb1ee582d3f64dcc3a7db33186e17a0d4ef41 100644 --- a/test.c +++ b/test.c @@ -85,30 +85,30 @@ void test_stack_pop(stack *s, int *val) { } int main() { - stack *s, *non_empty_stack; + stack s, non_empty_stack; int size = 10, value_to_add = 7; int *val; printf("Starting the tests...\n"); // Test init and destroy - test_stack_init(s, size); - test_stack_destroy(s); + test_stack_init(&s, size); + test_stack_destroy(&s); // Reinitialization - stack_init(s, size); - stack_init(non_empty_stack, 3); - non_empty_stack->data[0] = 1; - non_empty_stack->top = non_empty_stack->data[0]; + stack_init(&s, size); + stack_init(&non_empty_stack, 3); + non_empty_stack.data[0] = 1; + non_empty_stack.top = non_empty_stack.data[0]; // Test the other functions - test_stack_is_empty(s); - test_stack_is_not_empty(non_empty_stack); - test_stack_peek(*s, val); - test_stack_push(s, value_to_add); - test_stack_pop(s, val); + test_stack_is_empty(&s); + test_stack_is_not_empty(&non_empty_stack); + test_stack_peek(s, val); + test_stack_push(&s, value_to_add); + test_stack_pop(&s, val); // Free the memory - stack_destroy(s); - stack_destroy(non_empty_stack); + stack_destroy(&s); + stack_destroy(&non_empty_stack); // End the tests printf("The tests are completed and were successful !\n");