Add strndup
Andreas Hauser
andy at splashground.de
Tue Jun 20 12:45:09 PDT 2006
Hoi,
this patch adds strndup(3) and makes strdup(3) use it.
--
Andy
http://ftp.fortunaty.net/DragonFly/inofficial/patches/strndup.patch
diff -r 818115c3be2b lib/libc/string/Makefile.inc
--- a/lib/libc/string/Makefile.inc Sun Jun 11 22:54:18 2006 +0000
+++ b/lib/libc/string/Makefile.inc Tue Jun 20 21:37:50 2006 +0200
@@ -34,6 +34,7 @@ MLINKS+=strcat.3 strncat.3
MLINKS+=strcat.3 strncat.3
MLINKS+=strcmp.3 strncmp.3
MLINKS+=strcpy.3 strncpy.3
+MLINKS+=strdup.3 strndup.3
MLINKS+=strerror.3 perror.3 strerror.3 sys_errlist.3 strerror.3 sys_nerr.3
MLINKS+=strerror.3 strerror_r.3
MLINKS+=strlcpy.3 strlcat.3
diff -r 818115c3be2b lib/libc/string/strdup.3
--- a/lib/libc/string/strdup.3 Sun Jun 11 22:54:18 2006 +0000
+++ b/lib/libc/string/strdup.3 Tue Jun 20 21:37:50 2006 +0200
@@ -38,6 +38,7 @@
.Os
.Sh NAME
.Nm strdup
+.Nm strndup
.Nd save a copy of a string
.Sh LIBRARY
.Lb libc
@@ -45,14 +46,22 @@
.In string.h
.Ft char *
.Fn strdup "const char *str"
+.Ft char *
+.Fn strdup "const char *str" "size_t len"
.Sh DESCRIPTION
The
.Fn strdup
-function
-allocates sufficient memory for a copy
+and
+.Fn strndup
+functions
+allocate sufficient memory for a copy
of the string
.Fa str ,
-does the copy, and returns a pointer to it.
+do the copy, and return a pointer to it. The
+.Fn strndup
+function copies
+.Fa len
+characters.
The pointer may subsequently be used as an
argument to the function
.Xr free 3 .
diff -r 818115c3be2b lib/libc/string/strdup.c
--- a/lib/libc/string/strdup.c Sun Jun 11 22:54:18 2006 +0000
+++ b/lib/libc/string/strdup.c Tue Jun 20 21:37:50 2006 +0200
@@ -40,14 +40,20 @@
#include <string.h>
char *
+strndup(const char *str, size_t len)
+{
+ char *copy;
+
+ if ((copy = malloc(len + 1)) == NULL)
+ return (NULL);
+ memcpy(copy, str, len);
+ copy[len + 1] = '\0';
+ return (copy);
+}
+
+char *
strdup(const char *str)
{
- size_t len;
- char *copy;
+ return strndup(str, strlen(str));
+}
- len = strlen(str) + 1;
- if ((copy = malloc(len)) == NULL)
- return (NULL);
- memcpy(copy, str, len);
- return (copy);
-}
More information about the Submit
mailing list