strcpy源码分析

/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   .  */

#include 
#include 
#include 

#undef strcpy
/**
 * strcpy和memcpy主要有以下3方面的区别。
1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy
 */
/* Copy SRC to DEST.  */
char *
strcpy (dest, src)
     char *dest;
     const char *src;
{
  char c;
  char *s = (char *) src;
  /**
   * 任意两个指针的差就是两者之间的距离。得到地址间的相对距离off后,就不需要再用绝对地址寻址了
   * 这样可以减少一次dest++
   */
  /**
   * 下面给出strcpy的一般实现:
   *       char * strcpy (char * dst, const char * src)
       {
           char * cp = dst;

           while( *cp++ = *src++ )
                   ;
           return( dst );
       }
   */
  const ptrdiff_t off = dest - s - 1;

  do
    {
      c = *s++;
      s[off] = c;
    }
  while (c != '\0');//使用do while是可以把'\0'字符也被复制过去了。

  return dest;
}
libc_hidden_builtin_def (strcpy)
如有任何疑问或者bug欢迎指出,邮箱[email protected]。更多内容参见https://github.com/demiaowu/rainrsc

你可能感兴趣的:(C)