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.
malloc: *** error for object 0x7ffc49c02850: pointer being freed was not allocated
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment