strndup

   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:  --------------------------------------------------------------------------------

转载于:https://my.oschina.net/lyr/blog/61829

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值