[!HAVE_DECL_STRNLEN]: Declare strnlen.
[gnulib.git] / lib / strndup.c
1 /* Copyright (C) 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
2
3    NOTE: The canonical source of this file is maintained with the GNU C Library.
4    Bugs can be reported to bug-glibc@prep.ai.mit.edu.
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include <stdio.h>
25 #include <sys/types.h>
26
27 #if defined _LIBC || defined STDC_HEADERS
28 # include <stdlib.h>
29 # include <string.h>
30 #else
31 char *malloc ();
32 #endif
33
34 #ifndef HAVE_DECL_STRNLEN
35 "this configure-time declaration test was not run"
36 #endif
37 #if !HAVE_DECL_STRNLEN
38 size_t strnlen ();
39 #endif
40
41 #undef __strndup
42 #undef strndup
43
44 #ifndef weak_alias
45 # define __strndup strndup
46 #endif
47
48 char *
49 __strndup (const char *s, size_t n)
50 {
51   size_t len = strnlen (s, n);
52   char *new = malloc (len + 1);
53
54   if (new == NULL)
55     return NULL;
56
57   new[len] = '\0';
58   return (char *) memcpy (new, s, len);
59 }
60 #ifdef weak_alias
61 weak_alias (__strndup, strndup)
62 #endif