From cbd536b369669a8080b2d4a5644ef7c2f80cf88f Mon Sep 17 00:00:00 2001 From: Kevin Jerebica Date: Sun, 25 Aug 2024 23:01:28 +0200 Subject: [PATCH] fix: check for existing string before mkstr --- README | 8 ++++---- data.c | 0 streecmp.c | 4 ++++ test.c | 11 ++++++----- 4 files changed, 14 insertions(+), 9 deletions(-) delete mode 100644 data.c diff --git a/README b/README index f013119..3d5fe39 100644 --- a/README +++ b/README @@ -15,22 +15,22 @@ TECHNICALS * data structure that represents a node of the tree struct nod *mknod(struct nod *prnt) * create a child node below given parent node - * returns: pointer to said node or NULL if fails + * returns: pointer to said node or NULL if function fails int mkstr(struct nod *rot, char *str) * fit string into tree if it does not already exist * warning: string has to be null-byte terminated - * returns: the assigned ID of the string or -1 if fails + * returns: the assigned ID of the string, 0 if string + is already inside tree, or -1 if function fails int gentree(struct nod *rot, char *strs) * generate tree from character seperated strings * warning: seperation character is '\n' - * returns: 0 if ok or -1 if fails + * returns: 0 if ok or -1 if function fails int streecmp(struct nod *rot, char *str) * traverse tree and search for str * returns: id of string or 0 if there is no match TODO - * Detect strings which are already inside the tree * Memory leaks * Alloc/free functions * NULL checking diff --git a/data.c b/data.c deleted file mode 100644 index e69de29..0000000 diff --git a/streecmp.c b/streecmp.c index 3486b60..67e5d50 100644 --- a/streecmp.c +++ b/streecmp.c @@ -39,6 +39,10 @@ struct nod *mknod(struct nod *nod, int loc) { int mkstr(struct nod *nod, char *str) { struct nod *target = nod->pool[*str]; if (target != NULL) { + if (*str == '\0') { + return 0; + } + return mkstr(target, str+1); } diff --git a/test.c b/test.c index d121785..bbeb4c5 100644 --- a/test.c +++ b/test.c @@ -136,14 +136,15 @@ int main(void) { int cnt = 1; for (char *tok = strtok(strs_cpy, "\n"); tok != NULL; tok - = strtok(NULL, "\n"), cnt++) { + = strtok(NULL, "\n")) { int found = streecmp(rot, tok); if (found == cnt) { - fprintf(stdout, "[+][%d\t] Success: could find" - " '%s' in tree\n", cnt, tok); + fprintf(stdout, "[+][%d/%d] Success: could find" + " '%s' in tree\n", cnt, found, tok); + cnt++; } else { - fprintf(stderr, "[-][%d\t] Error: could not find" - " '%s' in tree\n", cnt, tok); + fprintf(stderr, "[-][%d/%d] Error: could not find" + " '%s' in tree\n", cnt, found, tok); } }