Back to index

cell-binutils  2.17cvs20070401
xstrndup.c
Go to the documentation of this file.
00001 /* Implement the xstrndup function.
00002    Copyright (C) 2005 Free Software Foundation, Inc.
00003    Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
00004 
00005 This file is part of the libiberty library.
00006 Libiberty is free software; you can redistribute it and/or
00007 modify it under the terms of the GNU Library General Public
00008 License as published by the Free Software Foundation; either
00009 version 2 of the License, or (at your option) any later version.
00010 
00011 Libiberty is distributed in the hope that it will be useful,
00012 but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 Library General Public License for more details.
00015 
00016 You should have received a copy of the GNU Library General Public
00017 License along with libiberty; see the file COPYING.LIB.  If
00018 not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
00019 Boston, MA 02110-1301, USA.  */
00020 
00021 /*
00022 
00023 @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n})
00024 
00025 Returns a pointer to a copy of @var{s} with at most @var{n} characters
00026 without fail, using @code{xmalloc} to obtain memory.  The result is
00027 always NUL terminated.
00028 
00029 @end deftypefn
00030 
00031 */
00032 
00033 #ifdef HAVE_CONFIG_H
00034 #include "config.h"
00035 #endif
00036 #include <sys/types.h>
00037 #ifdef HAVE_STRING_H
00038 #include <string.h>
00039 #else
00040 # ifdef HAVE_STRINGS_H
00041 #  include <strings.h>
00042 # endif
00043 #endif
00044 #include "ansidecl.h"
00045 #include "libiberty.h"
00046 
00047 char *
00048 xstrndup (const char *s, size_t n)
00049 {
00050   char *result;
00051   size_t len = strlen (s);
00052 
00053   if (n < len)
00054     len = n;
00055 
00056   result = XNEWVEC (char, len + 1);
00057 
00058   result[len] = '\0';
00059   return (char *) memcpy (result, s, len);
00060 }