Skip to content

Instantly share code, notes, and snippets.

@begriffs
Created October 3, 2020 18:22
Show Gist options
  • Save begriffs/e8e5d79d2882fdc67329dc92c6e08508 to your computer and use it in GitHub Desktop.
Save begriffs/e8e5d79d2882fdc67329dc92c6e08508 to your computer and use it in GitHub Desktop.

Revisions

  1. begriffs created this gist Oct 3, 2020.
    62 changes: 62 additions & 0 deletions fail.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    #define _POSIX_C_SOURCE 200112L

    #include <search.h>
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    struct st_symbol
    {
    char *name;
    int type;
    };

    int always_equal(const void *a, const void *b)
    {
    (void) a;
    (void) b;
    return 0;
    }

    int name_cmp(const void *a, const void* b)
    {
    const struct st_symbol *u = a, *v = b;
    return strcmp(u->name, v->name);
    }

    bool st_add(struct st_symbol **tab, const char *s, int type)
    {
    struct st_symbol *y = malloc(sizeof *y);
    if (!y) abort();
    y->name = strdup(s);
    y->type = type;
    if (!y->name) abort();

    struct st_symbol **node = tsearch(y, (void **)tab, name_cmp);
    if (!node)
    abort();
    return true;
    }

    void st_free(struct st_symbol **tab)
    {
    while (*tab)
    {
    struct st_symbol *item = *tab;
    printf("deleting node: string = %s\n", item->name);
    tdelete(item, (void **)tab, always_equal);
    free(item->name);
    free(item);
    }
    }

    int main(void)
    {
    struct st_symbol *g_words = NULL;

    st_add(&g_words, "hi", 1);
    st_free(&g_words);

    return 0;
    }