From 14b33ae9c00f74a24a00aaece88b22af0955379e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= Date: Mon, 4 Feb 2019 18:23:51 +0100 Subject: Fix most memmory errors. --- linked_list.inc.h | 68 ++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 23 deletions(-) (limited to 'linked_list.inc.h') diff --git a/linked_list.inc.h b/linked_list.inc.h index b6942a94..be51e582 100644 --- a/linked_list.inc.h +++ b/linked_list.inc.h @@ -6,28 +6,35 @@ INIT_F ( LLIST(TYPE) ) { this->length = 0; NEW(LINK(TYPE), head); NEW(LINK(TYPE), tail); - this->head = head; - this->tail = tail; - head->after = tail; + this->head = head; + this->tail = tail; + head->after = tail; tail->before = head; - this->cur = head; + this->cur = head; + return 0; +} + +FREE_F (LINK(TYPE)) { + if (this->before != NULL) this->before->after = NULL; + if (this->after != NULL) this->after->before = NULL; + // TODO how much of value do I really wanna free? + // Should I implement some form of shared pointer? + if (this->value != NULL) FFREE(TYPE, this->value); return 0; } FREE_F( LLIST(TYPE) ) { - LINK(TYPE) *node, *next; - node = this->head->after; - while (node->after != NULL) { - next = node->after; - if (node->value != NULL) { - FFREE(TYPE, node->value); - } - // free(node); - node = next; + + LINK(TYPE) *n, *next; + n = this->head; + while ( n != NULL ) { + next = n->after; + FFREE(LINK(TYPE), n); + n = next; } - free (this->head); - free (this->tail); - this->length = 0; + + this->length = -1; + return 0; } @@ -46,16 +53,16 @@ INIT_F ( LINK(TYPE), TYPE* val ) { } int LLIST_CONS(TYPE) ( LLIST(TYPE)* lst, TYPE* val) { - NEW(LINK(TYPE), l, val); + NEW(LINK(TYPE), link, val); - l->after = lst->head->after; - lst->head->after = l; - l->after->before = l; - l->before = lst->head; + link->after = lst->head->after; + lst->head->after = link; + link->after->before = link; + link->before = lst->head; ++lst->length; // TODO do I want to change that? - lst->cur = l; + lst->cur = link; return 0; } @@ -76,6 +83,8 @@ int DEEP_COPY(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* src ) { /* * TODO * this or cons links wrong, creating infinite loops. + * TODO + * or maybe not */ int APPEND(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* new ) { @@ -85,7 +94,7 @@ int APPEND(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* new ) { dest->tail = new->tail; dest->length += new->length; - // free(old_tail); + free(old_tail); // free(new->head); /* @@ -96,4 +105,17 @@ int APPEND(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* new ) { return 0; } +int SIZE(LLIST(TYPE)) ( LLIST(TYPE)* llist ) { + int size = 0; + LINK(TYPE)* l = llist->head->after; + while (l->after != NULL) { + ++size; + } + return size; +} + +int EMPTY(LLIST(TYPE)) ( LLIST(TYPE)* llist ) { + return llist->head->after == llist->tail; +} + #endif /* TYPE */ -- cgit v1.2.3