1 版权声明:本文为博主原创文章,未经博主允许不得转载。    https://blog.csdn.net/koozxcv/article/details/49306751
 2 strcpy和strdup比较和详解
 3 
 4 函数和功能描述:
 5 
 6extern char *strdup(char *s);
 7 
 8 头文件:string.h
 9 
10 功能: 将串拷贝到新建的位置处
11 
12 说 明:strdup不是标准的c函数。strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。
13 返回值:返回一个指针,指向为复制字符串分配的空间;如果分配空间失败,则返回NULL值。
14 
15  // strdup.c
16 
17 #include <syslib.h>
18 
19 #include <string.h>
20 
21 main() 
22 
23 24 
25  char *s="Golden Global View";
26 
27 char *d;
28 
29  d=strdup(s);
30 
31 printf("%s",d);
32 
33 return 0;
34 
35 }
36 
37char *strcpy(char* dest, const char *src);
38 
39 头文件:#include <string.h>和 #include <stdio.h>
40 
41 功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
42 
43 说明:strcpy是标准的C语言标准库函数。src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
44 
45 返回值:返回指向dest的指针。
46 
47  举例:
48 
49  // strcpy.     
50 
51       #include <syslib.h>
52 
53  #include <string.h>     
54 
55  main()
56 
57   {        
58 
59 char *s="Golden Global View";
60 
61 char d[20]; 
62 
63 printf("%s",d);       
64 
65  return 0;    
66 
67   }
68 
69 总结:
70 
71 1.strdup不是标准的c函数,strcpy是标准的c函数,使用时注意场合。
72 2.strdup可以直接把要复制的内容复制给没有初始化的指针,因为它会自动分配空间给目的指针,strcpy的目的指针一定是已经分配内存的指针。
73 3.strdup用完要free()函数释放内存,否则内存泄露 。
74  4.使用strcpy必须事先确定src大小,可以先strlen判断src的大小,之后为dest申请空间,之后再strcpy就不会有问题了。
75 --------------------- 
76 作者:koozxcv 
77 来源:CSDN 
78 原文:https://blog.csdn.net/koozxcv/article/details/49306751 
79 版权声明:本文为博主原创文章,转载请附上博文链接!

 

posted on 2019-05-08 11:48  寒舟独饮  阅读(667)  评论(0)    收藏  举报