From f9dd9bc766fb9f3e806ce72db46ed4169887cab3 Mon Sep 17 00:00:00 2001 From: Michael Tryby Date: Wed, 10 Apr 2019 10:57:55 -0400 Subject: [PATCH] Clean up and inline comments --- src/util/list.c | 9 ++++++++- src/util/list.h | 4 ++-- tests/util/test_list.cpp | 1 + 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/util/list.c b/src/util/list.c index 47bded9..286172a 100644 --- a/src/util/list.c +++ b/src/util/list.c @@ -24,7 +24,7 @@ #include "list.h" -list_t *create_list(int elementSize, freeFunction freeFn) +list_t *create_list(size_t elementSize, freeFunction freeFn) { list_t *list; list = (list_t *)calloc(1, sizeof(list_t)); @@ -103,20 +103,27 @@ void for_each_list(list_t *list, listIterator iterator) } void *head_list(list_t *list, bool removeFromList) +// +// Warning: Caller is responsible for freeing the node->data returned. +// { assert(list->head != NULL); listNode *node = list->head; void *element = (void *)malloc(list->elementSize); + // Copying pointer to node->data memcpy(element, node->data, list->elementSize); if(removeFromList) { + // Disconnecting head node list->head = node->next; list->logicalLength--; + // Freeing pointer to node->data and node free(node->data); free(node); } + // Now element points to data formerly pointed to by node return element; } diff --git a/src/util/list.h b/src/util/list.h index 311234f..0a84753 100644 --- a/src/util/list.h +++ b/src/util/list.h @@ -33,7 +33,7 @@ typedef struct _listNode { typedef struct { int logicalLength; - int elementSize; + size_t elementSize; listNode *head; listNode *tail; freeFunction freeFn; @@ -44,7 +44,7 @@ typedef struct { @brief Initializes a linked list to store elements of elementSize and to call freeFunction for each element when destroying a list. */ -list_t *create_list(int elementSize, freeFunction freeFn); +list_t *create_list(size_t elementSize, freeFunction freeFn); /** @brief Frees dynamically allocated nodes and optionally calls freeFunction diff --git a/tests/util/test_list.cpp b/tests/util/test_list.cpp index f41a2e8..97a3ea0 100644 --- a/tests/util/test_list.cpp +++ b/tests/util/test_list.cpp @@ -111,6 +111,7 @@ BOOST_FIXTURE_TEST_CASE(test_head_list, FixtureStrings) { BOOST_CHECK(check_string(*(char **)temp, "David")); BOOST_CHECK(size_list(list) == 4); + // To free a node, free both the data and reference to data free_string(temp); free(temp); }