This is the mail archive of the libc-hacker@sources.redhat.com mailing list for the glibc project.

Note that libc-hacker is a closed list. You may look at the archives of this list, but subscription and posting are not open.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

[PATCH] Fix strndup


Hi!

strndup("abc ", 3) would return "ab"...

2001-11-02  Jakub Jelinek  <jakub@redhat.com>

	* string/bits/string2.h (__strndup): If n is smaller than len, set
	len to n + 1.
	* string/tester.c (test_strndup): New function.
	(main): Call it.

--- libc/string/bits/string2.h.jj	Fri Nov  2 20:52:48 2001
+++ libc/string/bits/string2.h	Fri Nov  2 20:54:56 2001
@@ -1216,7 +1216,7 @@ extern char *__strndup (__const char *__
 			  size_t __n = (n);				      \
 			  char *__retval;				      \
 			  if (__n < __len)				      \
-			    __len = __n;				      \
+			    __len = __n + 1;				      \
 			  __retval = (char *) malloc (__len);		      \
 			  if (__retval != NULL)				      \
 			    {						      \
--- libc/string/tester.c.jj	Sun Aug 26 19:19:33 2001
+++ libc/string/tester.c	Fri Nov  2 21:03:43 2001
@@ -1257,6 +1257,30 @@ test_bzero (void)
 }
 
 static void
+test_strndup (void)
+{
+  char *p, *q;
+  it = "strndup";
+  p = strndup("abcdef", 12);
+  check(p != NULL, 1);
+  if (p != NULL)
+    {
+      equal(p, "abcdef", 2);
+      q = strndup(p + 1, 2);
+      check(q != NULL, 3);
+      if (q != NULL)
+	equal(q, "bc", 4);
+      free (q);
+    }
+  free (p);
+  p = strndup("abc def", 3);
+  check(p != NULL, 5);
+  if (p != NULL)
+    equal(p, "abc", 6);
+  free (p);
+}
+
+static void
 test_bcmp (void)
 {
   it = "bcmp";
@@ -1382,6 +1406,9 @@ main (void)
   /* bcmp - somewhat like memcmp.  */
   test_bcmp ();
 
+  /* strndup.  */
+  test_strndup ();
+
   /* strerror - VERY system-dependent.  */
   test_strerror ();
 

	Jakub


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]