C語言中函數strcpy ,strncpy ,strlcpy的用法【轉】


轉自:http://blog.chinaunix.net/uid-20797562-id-99311.html

strcpy ,strncpy ,strlcpy的用法
好多人已經知道利用strncpy替代strcpy來防止緩沖區越界。
但是如果還要考慮運行效率的話,也許strlcpy是一個更好的方式。
1. strcpy

我們知道,strcpy 是依據 \0 作為結束判斷的,如果 to 的空間不夠,則會引起 buffer overflow。strcpy 常規的實現代碼如下(來自 OpenBSD 3.9):

char *
strcpy(char *to, const char *from)
{
       char *save = to;

       for (; (*to = *from) != '\0'; ++from, ++to);
       return(save);
}

但通常,我們的 from 都來源於用戶的輸入,很可能是非常大的一個字符串,因此 strcpy 不夠安全。


2. strncpy

在 ANSI C 中,strcpy 的安全版本是 strncpy。

char *strncpy(char *s1, const char *s2, size_t n);

但 strncpy 其行為是很詭異的(不符合我們的通常習慣)。標准規定 n 並不是 sizeof(s1),而是要復制的 char 的個數。一個最常見的問題,就是 strncpy 並不幫你保證 \0

結束。

char buf[8];
strncpy( buf, "abcdefgh", 8 );

看這個程序,buf 將會被 "abcdefgh" 填滿,但卻沒有 \0 結束符了。

另外,如果 s2 的內容比較少,而 n 又比較大的話,strncpy 將會把之間的空間都用 \0 填充。這又出現了一個效率上的問題,如下:

char buf[80];
strncpy( buf, "abcdefgh", 79 );

上面的 strncpy 會填寫 79 個 char,而不僅僅是 "abcdefgh" 本身。


strncpy 的標准用法為:(手工寫上 \0)

strncpy(path, src, sizeof(path) - 1);
path[sizeof(path) - 1] = '\0';
len = strlen(path);


3. strlcpy

// Copy src to string dst of size siz. At most siz-1 characters
// will be copied. Always NUL terminates (unless siz == 0).
// Returns strlen(src); if retval >= siz, truncation occurred.
size_t
strlcpy(char *dst, const char *src, size_t siz);

而使用 strlcpy,就不需要我們去手動負責 \0 了,僅需要把 sizeof(dst) 告之 strlcpy 即可:

strlcpy(path, src, sizeof(path));
len = strlen(path);

if ( len >= sizeof(path) )
       printf("src is truncated.");

並且 strlcpy 傳回的是 strlen(str),因此我們也很方便的可以判斷數據是否被截斷。

[* 一點點歷史 *]

strlcpy 並不屬於 ANSI C,至今也還不是標准。

strlcpy 來源於 OpenBSD 2.4,之后很多 unix-like 系統的 libc 中都加入了 strlcpy 函數,我個人在 FreeBSD、Linux 里面都找到了 strlcpy。(Linux使用的是 glibc,

glibc里面有 strlcpy,則所有的 Linux 版本也都應該有 strlcpy)

但 Windows 下是沒有 strlcpy 的,對應的是strcpy_s函數 
///////////////////////////////////////////////////////////////////////////
strncpy     
      原型:extern   char   *strncpy(char   *dest,   char   *src,   int   n);   
                    
      用法:#include      
        
      功能:把src所指由NULL結束的字符串的前n個字節復制到dest所指的數組中。   
        
      說明:   
                  如果src的前n個字節不含NULL字符,則結果不會以NULL字符結束。   
                  如果src的長度小於n個字節,則以NULL填充dest直到復制完n個字節。   
                  src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。   
                  返回指向dest的指針。   
        
      舉例:   
    
    
              //   strncpy.c   
                
              #include      
              #include      
    
              main()   
              {   
                  char   *s="Golden   Global   View";   
                  char   *d="Hello,   GGV   Programmers";   
                  char   *p=strdup(s);   
                    
                  clrscr();   
                  textmode(0x00);     //   enable   6   lines   mode   
                                    
                  strncpy(d,s,strlen(s));   
                  printf("%s\n",d);   
                    
                  strncpy(p,s,strlen(d));   
                  printf("%s",p);   
                    
    
                  getchar();   
                  return   0;   
              }   
------------------------------   
memcpy     
      原型:extern   void   *memcpy(void   *dest,   void   *src,   unsigned   int   count);   
    
      用法:#include      
        
      功能:由src所指內存區域復制count個字節到dest所指內存區域。   
        
      說明:src和dest所指內存區域不能重疊,函數返回指向dest的指針。   
        
      舉例:   
    
              //   memcpy.c   
                
              #include      
              #include      
    
              main()   
              {   
                  char   *s="Golden   Global   View";   
                  char   d[20];   
                    
                  clrscr();   
                    
                  memcpy(d,s,strlen(s));   
                  d[strlen(s)]=0;   
                  printf("%s",d);   
    
                  getchar();   
                  return   0;   
              }  

函數名: strdup 
功  能: 將串拷貝到新建的位置處 
用  法: char *strdup(char *str); 
程序例:

#include  
#include  
#include

int main(void) 
 { 
    char *dup_str, *string = "abcde";

    dup_str = strdup(string); 
    printf("%s\n", dup_str); 
    free(dup_str);

    return 0; 
 }

clrscr在conio.h里面。 
函數名: clrscr 
功能: 清除文本模式窗口 
用法: void clrscr(void); 

程序例: 
#include 
int main(void) 
{int i; 
clrscr(); 
for (i = 0; i < 20; i++) 
cprintf("%d\r\n", i); 
cprintf("\r\nPress any key to clear screen"); 
getch(); 
clrscr(); 
cprintf("The screen has been cleared!"); 
getch(); 
return 0; 
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM