Implement strdup

This commit is contained in:
bumbread 2022-06-24 12:45:55 +11:00
parent 25db1abb6e
commit 29a98bf8a3
2 changed files with 27 additions and 6 deletions

View File

@ -7,19 +7,23 @@
#include <stddef.h>
#if !defined(NULL)
#define NULL ((void *)0)
#define NULL ((void *)0)
#endif
#if !defined(__STDC_LIB_EXT1__)
#define __STDC_LIB_EXT1__
typedef int errno_t;
typedef size_t rsize_t;
#define __STDC_LIB_EXT1__
typedef int errno_t;
typedef size_t rsize_t;
#endif
#if __STDC_WANT_SECURE_LIB__ == 1
#if !defined(__STDC_WANT_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#if !defined(__STDC_WANT_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#endif
#endif
#if !defined(__STDC_ALLOC_LIB__)
#define __STDC_ALLOC_LIB__
#endif
// int _wcsicmp(const wchar_t *string1, const wchar_t *string2);
@ -50,7 +54,9 @@ size_t strlen(const char *s);
// Linux extension: reentrant strtok
char *strtok_r(char *restrict s1, const char *restrict s2, char **restrict ctx);
// Extension 1
#if __STDC_WANT_LIB_EXT1__ == 1
errno_t memcpy_s(void *restrict s1, rsize_t s1max, const void *restrict s2, rsize_t n);
errno_t memmove_s(void *s1, rsize_t s1max, const void *s2, rsize_t n);
errno_t strcpy_s(char *restrict s1, rsize_t s1max, const char *restrict s2);
@ -62,4 +68,12 @@ errno_t memset_s(void *s, rsize_t smax, int c, rsize_t n);
errno_t strerror_s(char *s, rsize_t maxsize, errno_t errnum);
size_t strerrorlen_s(errno_t errnum);
size_t strnlen_s(const char *str, size_t strsz);
#endif
// Extension 2
#if __STDC_WANT_LIB_EXT2__ == 1
char *strdup(const char *str1);
#endif

View File

@ -236,3 +236,10 @@ size_t strnlen_s(const char *s, size_t maxsize) {
}
return i;
}
char *strdup(const char *str1) {
size_t len = strlen(str1);
char *copy = calloc(len+1, 1);
strcpy(copy, str1);
return copy;
}