From a863042b12398a2c474ac8629a6683a8ebd23266 Mon Sep 17 00:00:00 2001
From: "dario.genga" <dario.genga@etu.hesge.ch>
Date: Tue, 23 Nov 2021 16:08:33 +0100
Subject: [PATCH] Add stack init and destroy

Also fixed some issues in the test file that were caused by the
initialization of a stack's pointer instead of a normal stack.
---
 stack.c |  9 +++++++--
 test.c  | 28 ++++++++++++++--------------
 2 files changed, 21 insertions(+), 16 deletions(-)

diff --git a/stack.c b/stack.c
index 4137848..1d8d39b 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 ae29034..380eb1e 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");
-- 
GitLab