From 9f0191845db87a479a6d4c9038c0c771b81ed688 Mon Sep 17 00:00:00 2001 From: fonkou Date: Tue, 2 Dec 2025 15:48:32 +0100 Subject: [PATCH] add testStack.c and test_number.c --- testStack.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++ test_number.c | 3 +++ 2 files changed, 76 insertions(+) create mode 100644 testStack.c create mode 100644 test_number.c diff --git a/testStack.c b/testStack.c new file mode 100644 index 0000000..25f89d0 --- /dev/null +++ b/testStack.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include "stack.h" + +// Helper: create int on heap +static int *make_int(int value) { + int *p = malloc(sizeof(int)); + if (!p) { + fprintf(stderr, "Memory allocation failed\n"); + exit(1); + } + *p = value; + return p; +} + +int main(void) { + + printf("Running stack unit tests...\n"); + + StackNode *stack = NULL; + + // --- Test 1: push() on empty stack --- + int *a = make_int(10); + stack = push(stack, a); + assert(stack != NULL); + assert(top(stack) == a); + assert(*(int*)top(stack) == 10); + + // --- Test 2: push() on non-empty stack --- + int *b = make_int(20); + stack = push(stack, b); + assert(top(stack) == b); + assert(*(int*)top(stack) == 20); + + // --- Test 3: pop() returns previous element --- + stack = pop(stack); // removes 20 + assert(top(stack) == a); + assert(*(int*)top(stack) == 10); + + // --- Test 4: pop() on single element returns NULL --- + stack = pop(stack); // removes 10 + assert(stack == NULL); + + // --- Test 5: pop() on empty stack returns NULL --- + stack = pop(stack); + assert(stack == NULL); + + // --- Test 6: clearStack() empties a multi-element stack --- + int *c = make_int(1); + int *d = make_int(2); + int *e = make_int(3); + stack = push(stack, c); + stack = push(stack, d); + stack = push(stack, e); + + clearStack(stack); + // stack pointer still points to old top; we must reset manually + stack = NULL; + + // no crash = success + + // free remaining data + free(a); + free(b); + free(c); + free(d); + free(e); + + printf("All tests passed successfully.\n"); + + return 0; +} diff --git a/test_number.c b/test_number.c new file mode 100644 index 0000000..d92535b --- /dev/null +++ b/test_number.c @@ -0,0 +1,3 @@ +// +// Created by kamtewil on 02.12.2025. +// \ No newline at end of file