1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "append.h"
#include <assert.h>

// BUG!!!!
//
// This version of the example had a bona fide bug.  I forgot to initialize
// the struct object on line 14.  The assert(…) on line 23 showed me the bug.

void append(int value, Node** a_head, Node** a_tail) {
    Node* new_tail = malloc(sizeof(*new_tail));
    // BUG!!!  Forgot to initialize the struct object here.
    if(*a_head == NULL) {  // List is empty.  Make it a list of size 1.
        *a_head = new_tail;
    }
    else {  // List is not empty.  Append to the end.
        (*a_tail) -> next = new_tail;
    }
    *a_tail = new_tail;

    assert((*a_tail) -> value == value);
    assert((*a_tail) -> next  == NULL);
    assert((*a_head) != NULL);  // Because if we added anything, list is not empty.
}

void print_list(Node* head) {
    for(Node* curr = head; curr != NULL; curr = curr -> next) {
        printf("[%d] ", curr -> value);
    }
    printf("\n");
}

void destroy_list(Node** a_head, Node** a_tail) {
    while(*a_head != NULL) {
        // Save the new head
        Node* new_head = (*a_head) -> next;

        // Free the old head
        free(*a_head);
        
        // Set 'head' to the address of new head
        *a_head = new_head;
    }

    assert(*a_head == NULL);

    *a_tail = NULL;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.