--- /dev/null
+#include "path.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+
+path init_path(const char *pth) {
+ if (!pth)
+ return NULL;
+ path ret = strdup(pth);
+ if (!ret)
+ err(1, "Failed to allocate memory in init_path, with '%s', aborting.\n", pth);
+ return ret;
+}
+
+void free_path(path *pth) {
+ if (pth && *pth) {
+ free(*pth);
+ *pth = NULL;
+ }
+}
+
+path cat_path(path dst, path suffix) {
+ if (!dst)
+ return suffix;
+ else if (!suffix)
+ return dst;
+
+ int dst_n = strlen(dst);
+ int suffix_n = strlen(suffix);
+ path new_dst = realloc(dst, dst_n + suffix_n + 2); // 2 because '\0' and / between the two if needed
+ if (!new_dst)
+ err(1, "Failed to reallocate memory in cat_path with dst='%s' and suffix='%s'", dst, suffix);
+ else
+ dst = new_dst;
+
+ if (dst[dst_n - 1] != '/') {
+ dst[dst_n] = '/';
+ dst[dst_n + 1] = '\0';
+ dst_n++;
+ }
+ if (suffix[0] == '/')
+ suffix++;
+
+ strcpy(dst + dst_n, suffix);
+ return dst;
+}
+
+// Tests
+// cc -Wall -Wextra -g -fsanitize=address path.c
+/*
+int main() {
+ {
+ path pth = init_path("/bin/");
+ pth = cat_path(pth, "/hello/world");
+ printf("%s\n", pth); // '/bin/hello/world'
+ free_path(&pth);
+ }
+ {
+ path pth = init_path("/bin");
+ pth = cat_path(pth, "hello/world");
+ printf("%s\n", pth); // '/bin/hello/world'
+ free_path(&pth);
+ }
+ {
+ path pth = init_path("/bin");
+ pth = cat_path(pth, "/hello/world");
+ printf("%s\n", pth); // '/bin/hello/world'
+ free_path(&pth);
+ }
+ {
+ path pth = init_path("/bin");
+ pth = cat_path(pth, "/hello/world");
+ printf("%s\n", pth); // '/bin/hello/world'
+ free_path(&pth);
+ }
+}
+*/