【glibc源码分析】--strcpy.c 字符串复制
生活随笔
收集整理的這篇文章主要介紹了
【glibc源码分析】--strcpy.c 字符串复制
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
strcpy是常用的字符串復(fù)制函數(shù),經(jīng)常在面試中考到。該文件位于glibc源碼的string目錄中。
在線資源路徑:
http://www.oschina.net/code/explore/glibc-2.9/string/strcpy.c
快速查看源碼如下:
1 /* Copyright (C) 1991, 1997, 2000, 2003 Free Software Foundation, Inc. 2 This file is part of the GNU C Library. 3 4 The GNU C Library is free software; you can redistribute it and/or 5 modify it under the terms of the GNU Lesser General Public 6 License as published by the Free Software Foundation; either 7 version 2.1 of the License, or (at your option) any later version. 8 9 The GNU C Library is distributed in the hope that it will be useful, 10 but WITHOUT ANY WARRANTY; without even the implied warranty of 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 Lesser General Public License for more details. 13 14 You should have received a copy of the GNU Lesser General Public 15 License along with the GNU C Library; if not, see 16 <http://www.gnu.org/licenses/>. */ 17 18 #include <stddef.h> /* 用到了ptrdiff_t */ 19 #include <string.h> 20 #include <memcopy.h> 21 #include <bp-checks.h> /* 定義了CHECK_BOUNDS_LOW和CHECK_BOUNDS_HIGH */ 22 23 #undef strcpy 24 25 /* Copy SRC to DEST. */ 26 char * 27 strcpy (dest, src) 28 char *dest; 29 const char *src; 30 { 31 char c; 32 char *__unbounded s = (char *__unbounded) CHECK_BOUNDS_LOW (src); 33 const ptrdiff_t off = CHECK_BOUNDS_LOW (dest) - s - 1; 34 size_t n; 35 36 do 37 { 38 c = *s++; 39 s[off] = c; /* 注意這種寫法, s[off]相當(dāng)于 *(s+off) */ 40 } 41 while (c != '\0'); 42 43 n = s - src; 44 (void) CHECK_BOUNDS_HIGH (src + n); 45 (void) CHECK_BOUNDS_HIGH (dest + n); 46 47 return dest; 48 } 49 libc_hidden_builtin_def (strcpy)?
以上的算法主要通過計算好兩個字符串的偏移量,然后循環(huán)遍歷src字符串,逐個賦值給dest的相應(yīng)位置;gnu的源碼一般都比較復(fù)雜,進(jìn)行了相應(yīng)的范圍檢查等處理;
?
再來看個簡單的,比較獨立的代碼:
1 char * strcpy(char * dest, const char * src) 2 { 3 if ( dest == NULL || src == NULL) // 地址檢查 4 { 5 return NULL; 6 } 7 8 if ( dest == src) // 相同地址檢查 9 { 10 return dest; 11 } 12 13 char * str = dest; 14 while ( ( *str++ = *src++ ) != '\0' ) // 循環(huán)復(fù)制 15 { 16 ; 17 } 18 19 return dest; 20 }注意,以上代碼采用了清爽的縮進(jìn)格式,保證代碼的清晰和可讀性; 第8行的檢查比較容易漏掉,這個是重點;
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/QuLory/archive/2012/09/17/glibc-strcpy.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的【glibc源码分析】--strcpy.c 字符串复制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PySpider问题记录http599
- 下一篇: 【leetcode-74】搜索二维矩阵