Provide strdup ourselves

This commit is contained in:
apio 2022-12-01 19:30:51 +01:00
parent aff867f667
commit 125ec8f063
2 changed files with 13 additions and 6 deletions

View File

@ -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 :)

View File

@ -7,10 +7,6 @@
#include <stdnoreturn.h>
#include <string.h>
#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);