Browse Source

string: split and fix strdup and strndup (DONE)

master
Lephenixnoir 8 months ago
parent
commit
8368ba70fd
Signed by: Lephenixnoir GPG Key ID: 1BBA026E13FC0495
  1. 1
      CMakeLists.txt
  2. 4
      STATUS
  3. 64
      src/libc/string/strdup.c
  4. 15
      src/libc/string/strndup.c

1
CMakeLists.txt

@ -146,6 +146,7 @@ set(SOURCES
src/libc/string/strncat.c
src/libc/string/strncmp.c
src/libc/string/strncpy.c
src/libc/string/strndup.c
src/libc/string/strnlen.c
src/libc/string/strrchr.c)

4
STATUS

@ -136,8 +136,8 @@ DONE: Function/symbol/macro is defined, builds, links, and is tested
- strchrnul: DONE
! - strcasecmp: TODO
! - strncasecmp: TODO
! - strdup: TODO
! - strndup: TODO
- strdup: DONE
- strndup: DONE
7.22 <tgmath.h> => GCC

64
src/libc/string/strdup.c

@ -1,64 +1,10 @@
#include <string.h>
#include <stdlib.h>
/*
** The strdup() function returns a pointer to a new string which is a
** duplicate of the string s. Memory for the new string is obtained with
** malloc(), and can be freed with free().
*/
char *strdup(const char *s)
char *strdup(char const *s)
{
size_t len;
void *dump;
// Check error
if (s == NULL)
return (NULL);
// Check len
len = strlen(s);
if (len == 0)
return (NULL);
// try to allocate the new area
dump = malloc(len);
if (dump == NULL)
return (NULL);
// dump the area and return
memcpy(dump, s, len);
return (dump);
size_t len = strlen(s) + 1;
char *copy = malloc(len);
if(copy) memcpy(copy, s, len);
return copy;
}
/*
** The strndup() function is similar, but copies at most n bytes. If s is longer
** than n, only n bytes are copied, and a terminating null byte ('\0') is added.
*/
char *strndump(const char *s, size_t n)
{
size_t len;
char *dump;
// Check error
if (s == NULL)
return (NULL);
// Check len
len = strnlen(s, n);
if (len == 0)
return (NULL);
// try to allocate the new area
dump = malloc(len);
if (dump == NULL)
return (NULL);
// dump the area, set the null byte and return
memcpy(dump, s, len);
dump[len - 1] = '\0';
return (dump);
}
//TODO: strdupa()
//TODO: strndupa()

15
src/libc/string/strndup.c

@ -0,0 +1,15 @@
#include <string.h>
#include <stdlib.h>
char *strndup(const char *s, size_t n)
{
size_t len = strnlen(s, n) + 1;
char *copy = malloc(len);
if(copy) {
memcpy(copy, s, len);
copy[len - 1] = 0;
}
return copy;
}
Loading…
Cancel
Save