From 2433d04fb3d3204cdc041ed7d9e2509ce2684ea7 Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Fri, 27 Mar 2020 16:46:57 -0400 Subject: Return NULL if input is NULL --- lib/str.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/str.c b/lib/str.c index 074bdb1..5bf95ec 100644 --- a/lib/str.c +++ b/lib/str.c @@ -705,6 +705,11 @@ char *normalize_space(char *s) { int add_whitespace = 0; char *result = s; char *tmp; + + if (s == NULL) { + return NULL; + } + if ((tmp = calloc(strlen(s) + 1, sizeof(char))) == NULL) { perror("could not allocate memory for temporary string"); return NULL; -- cgit From d0095b6d304bba14d0f93185939ce864843fa152 Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Fri, 27 Mar 2020 16:47:19 -0400 Subject: Add normalize_space test --- tests/test_str_normalize_space.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 tests/test_str_normalize_space.c diff --git a/tests/test_str_normalize_space.c b/tests/test_str_normalize_space.c new file mode 100644 index 0000000..286353d --- /dev/null +++ b/tests/test_str_normalize_space.c @@ -0,0 +1,29 @@ +#include "spm.h" +#include "framework.h" + +const char *testFmt = "case: '%s': returned '%s', expected '%s'\n"; +struct TestCase testCase[] = { + {.caseValue.sptr = "no extra whitespace in the string", .truthValue.sptr = "no extra whitespace in the string"}, + {.caseValue.sptr = "two extra spaces in the string", .truthValue.sptr = "two extra spaces in the string"}, + {.caseValue.sptr = "three extra spaces in the string", .truthValue.sptr = "three extra spaces in the string"}, + {.caseValue.sptr = " leading whitespace", .truthValue.sptr = "leading whitespace"}, + {.caseValue.sptr = "trailing whitespace ", .truthValue.sptr = "trailing whitespace"}, + {.caseValue.sptr = " leading and trailing whitespace ", .truthValue.sptr = "leading and trailing whitespace"}, + {.caseValue.sptr = " varying degrees of whitespace everywhere ", .truthValue.sptr = "varying degrees of whitespace everywhere"}, + {.caseValue.sptr = "nowhitespace", .truthValue.sptr = "nowhitespace"}, + {.caseValue.sptr = NULL, .truthValue.sptr = NULL}, +}; +size_t numCases = sizeof(testCase) / sizeof(struct TestCase); + +int main(int argc, char *argv[]) { + for (size_t i = 0; i < numCases; i++) { + if (testCase[i].caseValue.sptr == NULL && testCase[i].truthValue.sptr == NULL) { + // null input is null output + continue; + } + char *result = strdup(testCase[i].caseValue.sptr); + normalize_space(result); + myassert(strcmp(result, testCase[i].truthValue.sptr) == 0, testFmt, testCase[i].caseValue.sptr, result, testCase[i].truthValue.sptr); + } + return 0; +} \ No newline at end of file -- cgit