From 8a4e0de6cc6a1df8b8efa46164c254adfba255ea Mon Sep 17 00:00:00 2001 From: duernbergerjo100488 Date: Thu, 11 Dec 2025 13:58:50 +0100 Subject: [PATCH] Test umstrukturiert --- stack.c | 6 +++--- test_stack.c | 30 +++++++++++++++++++----------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/stack.c b/stack.c index 0d54b55..9891622 100644 --- a/stack.c +++ b/stack.c @@ -8,8 +8,8 @@ StackNode *push(StackNode *stack, void *data) if(node == NULL) return stack; // allocation failed -> return unchanged stack - node->data = data; // Set the data for the new node - node->next = stack; // New node points to the previous top of the stack + node->data = data; // Setze Daten + node->next = stack; // Setze nächsten Knoten auf aktuellen Stack return node; } @@ -21,7 +21,7 @@ StackNode *pop(StackNode *stack) return NULL; StackNode *next = stack->next; - // Do NOT free stack->data here; caller owns the pointed data + // Speicher des aktuellen Knotens freigeben free(stack); return next; } diff --git a/test_stack.c b/test_stack.c index a89ddd6..91d187a 100644 --- a/test_stack.c +++ b/test_stack.c @@ -8,37 +8,45 @@ int main(void) StackNode *s = NULL; // push 3 integers - int *a = malloc(sizeof(int)); *a = 1; s = push(s, a); - int *b = malloc(sizeof(int)); *b = 2; s = push(s, b); - int *c = malloc(sizeof(int)); *c = 3; s = push(s, c); + int *a = malloc(sizeof(int)); + *a = 1; + s = push(s, a); + int *b = malloc(sizeof(int)); + *b = 2; + s = push(s, b); + int *c = malloc(sizeof(int)); + *c = 3; + s = push(s, c); - // top should be c (3) + // oben liegt c (3) int *topv = (int *)top(s); if(topv == NULL || *topv != 3) { fprintf(stderr, "stack top expected 3\n"); return 1; } - // pop -> now top should be 2 + // oben liegt nun 2 s = pop(s); topv = (int *)top(s); if(topv == NULL || *topv != 2) { fprintf(stderr, "stack top expected 2 after pop\n"); return 2; } - // pop -> now top should be 1 + // oben liegt nun 1 s = pop(s); topv = (int *)top(s); if(topv == NULL || *topv != 1) { fprintf(stderr, "stack top expected 1 after pop\n"); return 3; } - // pop last + // letzen Stapelinhalt holen s = pop(s); if(s != NULL) { fprintf(stderr, "stack expected empty after popping all\n"); return 4; } - // free stored data (stack does not free data) - free(a); free(b); free(c); + // Eigenen Speicher freigeben + free(a); + free(b); + free(c); - // test clearStack on empty and small stacks + // test clearStack mit leerem Stack s = push(s, malloc(sizeof(int))); s = push(s, malloc(sizeof(int))); clearStack(s); // clearStack must free nodes but not payload; free payloads not necessary because we leaked intentionally for test of API // Note: above payloads are not freed (stack API spec); this test ensures clearStack doesn't crash. - // Success + // Funktioniert alles printf("test_stack: OK\n"); return 0; }