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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ustr.h"

/*
 * List node for storing a unique string as element
 */
struct Node
{
    struct Node *next;
    struct UStr ustr;
};

/*
 * list head: list points to the first list node
 */
static struct Node *list;

const struct UStr *
UStrAdd_(const char *s, bool *added)
{
    size_t len = strlen(s);

    /*
     * if added is the null pointer it gets ignored. Otherwise initialized with
     * true.
     */
    if (added) {
        *added = true;
    }

    /*
     * Search in list if it already contains string s
     */
    for (struct Node *n = list; n; n = n->next) {
        /*
         * TODO:
         * - Check if node n contains the string
         * - If this is the case:
         *    - If added is not the null pointer set *added to false
         *    - return a pointer to the unique string object stored in this node
         */

    }

    /*
     * String needs to be added
     */
    struct Node *n = 0; // <- TODO: Allocate a sufficiently large memory block
                        //          for a node that can store a string element
                        //          with length len.
                        //          Do not forget the null byte!
    if (!n) {
        fprintf(stderr, "makeUStr: out of memory\n");
        abort();
    }

    /*
     * Initialize the unique string object stored in this node:
     */
    n->ustr.len = len;
    // TODO: Initialize also n->ustr.cstr by copying s into this buffer

    /*
     * TODO: Append the new node to the head of the list. I.e. the new node
     *       will become the new head of the list. The successor of the new
     *       node will be the old list head.
     */

    /*
     * Return a pointer to the unique string object
     */
    return &n->ustr;
}

const struct UStr *
UStrAdd(const char *s)
{
    return UStrAdd_(s, 0);
}

void
UStrPrintPool(void)
{
    for (struct Node *n = list; n; n = n->next) {
        printf("%s\n", n->ustr.cstr);
    }
}