From f1b0595ef2549c18b995f182a8ed8e6e44b9cd04 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Mon, 6 Jul 2020 11:13:24 -0400 Subject: Fix double ended queue did not print free strings Because it is possible for to_string function to generate a new string here and nothing else sees it after printing it is not guaranteed to be freed leading to a memory leak. This does mean that if the string is internal to a struct and expected to be used later then to_string should duplicate said string (as noted in the documentation). --- collections/double_ended_queue/double_ended_queue.adoc | 7 +++++-- collections/double_ended_queue/double_ended_queue.c | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/collections/double_ended_queue/double_ended_queue.adoc b/collections/double_ended_queue/double_ended_queue.adoc index 52a085f..5daf03e 100644 --- a/collections/double_ended_queue/double_ended_queue.adoc +++ b/collections/double_ended_queue/double_ended_queue.adoc @@ -1,7 +1,7 @@ Double Ended Queue ================== Tucker Evans -v1.0.1, 2020-06-10 +v1.0.2, 2020-07-06 A double ended queue implemented in a circular buffer. @@ -514,6 +514,9 @@ Prints out the contents of the queue +self+ to +stdout+ (surounded by square bra function that takes a pointer to the type of elements stored in +self+ and returns a string representation. +NOTE: Strings are freed after printing, therefore +strdup()+ should be used on +any strings that are not for the sole purpose of printing here. + Examples ^^^^^^^^ [source,c] @@ -524,7 +527,7 @@ Examples char* to_string(str) void *str; { - return str; + return strdup(str); } int main() diff --git a/collections/double_ended_queue/double_ended_queue.c b/collections/double_ended_queue/double_ended_queue.c index 28ed9dc..c08169d 100644 --- a/collections/double_ended_queue/double_ended_queue.c +++ b/collections/double_ended_queue/double_ended_queue.c @@ -147,12 +147,15 @@ deq *root; char* to_string(void*); { int i, size;; + char *tmp; size = deq_size(root); printf("["); for (i = 0; i < size; i++) { - printf("%s,", to_string(deq_index(root, i))); + printf("%s,", tmp = to_string(deq_index(root, i))); + free(tmp); + tmp = NULL; } printf("\b]\n"); } -- cgit v1.1