strdup

来源:互联网 发布:几米漫画推荐知乎 编辑:程序博客网 时间:2024/05/20 03:46
头文件:#include <string.h>

定义函数:char * strdup(const char *s);


使用man来看一下:

       The strdup() function returns a pointer to a new string which is a duplicate of the string s.  Memory for the new string is obtained
       with malloc(3), and can be freed with free(3).


       The strndup() function is similar, but copies at most n bytes.  If s is longer than n, only n bytes are copied,  and  a  terminating
       null byte ('\0') is added.


函数说明:strdup()会先用maolloc()配置与参数s 字符串相同的空间大小,然后将参数s 字符串的内容复制到该内存地址,然后把该地址返回。该地址最后可以利用free()来释放。

返回值:返回一字符串指针,该指针指向复制后的新字符串地址。若返回NULL 表示内存不足。


这个函数的应用场景一般是在保存永久信息,也就是说一般不会使用free来释放,比如说公共的配置信息。


0 0
原创粉丝点击