From 125ec8f063b9c33ce2e2e8b9932ea27bff1f8aa6 Mon Sep 17 00:00:00 2001 From: apio Date: Thu, 1 Dec 2022 19:30:51 +0100 Subject: [PATCH] Provide strdup ourselves --- README.md | 2 +- src/util.c | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 358864f..3229779 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Tiny and easy-to-use C library to parse tar (specifically, the newer [USTAR](htt No third-party dependencies, only a minimally capable standard C library (file IO, number parsing, malloc() and friends, string functions). -Aims to be as portable between systems as possible (has its own implementation of some non-standard functions, such as [strlcpy](https://linux.die.net/man/3/strlcpy) or [strndup](https://linux.die.net/man/3/strndup)), but that still needs some work (minitar still depends on some POSIX functions, such as [basename](https://linux.die.net/man/3/basename) (not present on Windows) and [strdup](https://linux.die.net/man/3/strdup) (named _strdup under MSVC)). +Aims to be as portable between systems as possible (has its own implementation of some non-standard functions, such as [strlcpy](https://linux.die.net/man/3/strlcpy) or [strndup](https://linux.die.net/man/3/strndup)), but that still needs some work (minitar still depends on some POSIX functions, such as [basename](https://linux.die.net/man/3/basename) (not present on Windows))). Very minimal and bloat-free, currently less than 500 lines :) diff --git a/src/util.c b/src/util.c index 4c396a6..55ea62d 100644 --- a/src/util.c +++ b/src/util.c @@ -7,10 +7,6 @@ #include #include -#ifdef _MSC_VER -#define strdup(p) _strdup(p) -#endif - // Default implementation for minitar_handle_panic(). Since it's declared weak, any other definition will silently // override this one :) __attribute__((weak)) noreturn void minitar_handle_panic(const char* message) @@ -52,6 +48,16 @@ static char* minitar_strndup(const char* orig, size_t max) return ptr; } +// Our own replacement for strdup(). +static char* minitar_strdup(const char* orig) +{ + size_t len = strlen(orig); + char* ptr = calloc(len + 1, 1); + if (!ptr) return NULL; + for (size_t i = 0; i < len; ++i) { *(ptr + i) = *(orig + i); } + return ptr; +} + // strcat, but for characters :) static void minitar_append_char(char* str, char c) { @@ -90,7 +96,8 @@ void minitar_parse_metadata_from_tar_header(const struct tar_header* hdr, struct metadata->path[256] = '\0'; } - char* mut_path = strdup(metadata->path); // basename modifies the string passed to it, so we need to make a copy. + char* mut_path = + minitar_strdup(metadata->path); // basename modifies the string passed to it, so we need to make a copy. if (!mut_path) minitar_panic("Failed to allocate memory"); char* bname = basename(mut_path);