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

@ -22,6 +22,10 @@ typedef size_t rsize_t;
#endif
#endif
#if !defined(__STDC_ALLOC_LIB__)
#define __STDC_ALLOC_LIB__
#endif
// int _wcsicmp(const wchar_t *string1, const wchar_t *string2);
void *memcpy(void *restrict s1, const void *restrict s2, size_t n);
@ -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;
}