From: Raphaƫl Gertz Date: Tue, 5 Jul 2016 16:35:22 +0000 (+0200) Subject: Add tree freeing to avoid valgrind lightning storm X-Git-Tag: v0.1~2 X-Git-Url: https://git.rapsys.eu/carabistouilles/commitdiff_plain/7b608ee0b9ca9000614e46412b3e64e7c3b6f0fd?ds=sidebyside Add tree freeing to avoid valgrind lightning storm --- diff --git a/README b/README index 898574b..59e7822 100644 --- a/README +++ b/README @@ -14,3 +14,6 @@ Run analyse.c: Run analyse.c tests: ./cunittest + +Valgrind check: +valgrind --leak-check=full --show-leak-kinds=all ./analyse sirens_fxt.txt diff --git a/analyse.c b/analyse.c index 1adcdd9..08b8e03 100644 --- a/analyse.c +++ b/analyse.c @@ -50,9 +50,12 @@ struct leaf { unsigned count; }; -/* Lookup leaf prototype */ +/* Lookup leaf function prototype */ struct leaf *lookupLeaf(void **, const char *, unsigned); +/* Freeing node function prototype */ +void freeTree(void *, unsigned); + /* Main function */ int main(int argc, char **argv) { @@ -140,6 +143,9 @@ int main(int argc, char **argv) { /* Read until end of file */ } while (ret != 0); + /* Free tree */ + freeTree(tree, 0); + /* Close file */ if (close(fd) == -1) { perror("Close failed"); @@ -153,6 +159,36 @@ int main(int argc, char **argv) { exit(EXIT_SUCCESS); } +/* Recursive freeing of node function */ +void freeTree(void *base, unsigned index) { + void *current = base, *next; + if (base != NULL) { + /* Branch level */ + if (index < 8) { + /* Free horizontaly */ + do { + /* Free children */ + if (((struct branch *)current)->child != NULL) { + freeTree(((struct branch *)current)->child, index + 1); + } + /* Free current and switch to next */ + next = ((struct branch *)current)->next; + free(current); + current = next; + } while (current != NULL); + /* Leaf level */ + } else { + /* Free horizontaly */ + do { + /* Free current and switch to next */ + next = ((struct leaf *)current)->next; + free(current); + current = next; + } while (current != NULL); + } + } +} + /* Recursive lookup and populate tree function */ struct leaf *lookupLeaf(void **base, const char *key, unsigned index) { /* Return leaf */