aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorErik Liodden <[email protected]>2017-11-15 00:23:55 +0100
committerErik Liodden <[email protected]>2017-11-15 16:01:16 +0100
commit40c2c710a89760ea462723f2c1a38c1f2b5c41b7 (patch)
treea640add04887cd93e4a2297a8b6e05ad4caef125
parent7ba882f940f352fb17698c32819575f1a51fce09 (diff)
downloadalgdat-40c2c710a89760ea462723f2c1a38c1f2b5c41b7.tar.gz
add free function to stack
the caller specify a function to free the element. freefn is expected to be NULL if no such function is needed (the values are stored directly on the elems array)
-rw-r--r--include/list.h5
-rw-r--r--src/misc/list.c12
2 files changed, 12 insertions, 5 deletions
diff --git a/include/list.h b/include/list.h
index a97b9b0..dd25559 100644
--- a/include/list.h
+++ b/include/list.h
@@ -17,10 +17,11 @@ struct stack {
size_t elem_size;
int log_length;
int alloc_length;
+ void (*freefn)(void *);
};
-void stack_init(struct stack *s, size_t elem_size);
-void stack_destroy(struct stack *s);
+void stack_init(struct stack *s, size_t elem_size, void (*freefn)(void *));
+void stack_dispose(struct stack *s);
void stack_push(struct stack *s, void *elem_addr);
void stack_pop(struct stack *s, void *elem_addr);
diff --git a/src/misc/list.c b/src/misc/list.c
index ff83889..b9efc0b 100644
--- a/src/misc/list.c
+++ b/src/misc/list.c
@@ -25,17 +25,23 @@ static void grow_stack(struct stack *s)
assert(s->elems != NULL);
}
-void stack_init(struct stack *s, size_t elem_size)
+void stack_init(struct stack *s, size_t elem_size, void (*freefn)(void *))
{
s->elem_size = elem_size;
s->log_length = 0;
s->alloc_length = 4;
s->elems = allocate(s->alloc_length * elem_size);
+ s->freefn = freefn;
}
-void stack_destroy(struct stack *s)
+void stack_dispose(struct stack *s)
{
- free(s);
+ int i;
+ if (s->freefn) {
+ for (i = 0; i < s->log_length; i++)
+ s->freefn((char *)s->elems + (i * s->elem_size));
+ }
+ free(s->elems);
}
void stack_push(struct stack *s, void *elem_addr)