1: strndup.c [plain text]
2:
3: --------------------------------------------------------------------------------
4:
5: /* Implement the strndup function.
6: Copyright (C) 2005 Free Software Foundation, Inc.
7: Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
8:
9: This file is part of the libiberty library.
10: Libiberty is free software; you can redistribute it and/or
11: modify it under the terms of the GNU Library General Public
12: License as published by the Free Software Foundation; either
13: version 2 of the License, or (at your option) any later version.
14:
15: Libiberty is distributed in the hope that it will be useful,
16: but WITHOUT ANY WARRANTY; without even the implied warranty of
17: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18: Library General Public License for more details.
19:
20: You should have received a copy of the GNU Library General Public
21: License along with libiberty; see the file COPYING.LIB. If
22: not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
23: Boston, MA 02110-1301, USA. */
24:
25: /*
26:
27: @deftypefn Extension char* strndup (const char *@var{s}, size_t @var{n})
28:
29: Returns a pointer to a copy of @var{s} with at most @var{n} characters
30: in memory obtained from @code{malloc}, or @code{NULL} if insufficient
31: memory was available. The result is always NUL terminated.
32:
33: @end deftypefn
34:
35: */
36:
37: #include "ansidecl.h"
38: #include <stddef.h>
39:
40: extern size_t strlen (const char*);
41: extern PTR malloc (size_t);
42: extern PTR memcpy (PTR, const PTR, size_t);
43:
44: char *
45: strndup (const char *s, size_t n)
46: {
47: char *result;
48: size_t len = strlen (s);
49:
50: if (n < len)
51: len = n;
52:
53: result = (char *) malloc (len + 1);
54: if (!result)
55: return 0;
56:
57: result[len] = '\0';
58: return (char *) memcpy (result, s, len);
59: }
60:
61: --------------------------------------------------------------------------------