C语言strdup函数

1 static RD_INLINE RD_UNUSED char *rd_strdup(const char *s) {
2 #ifndef _MSC_VER
3     char *n = strdup(s);
4 #else
5     char *n = _strdup(s);
6 #endif
7     assert(n);
8     return n;
9 }
1 test_topics_sh = rd_strdup(val);

strdup()函数是c语言中常用的一种字符串拷贝库函数,一般和free()函数成对出现。

外文名
strdup
头文件
string.h
功 能
将串拷贝到新建的位置处
属 性
字符串拷贝库函数

原型:

extern char *strdup(char *s);
头文件:string.h

说明:

功 能: 将串拷贝到新建的位置处
strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。
 

返回值:


返回一个指针,指向为复制字符串分配的空间;如果分配空间失败,则返回NULL值。
 

Example:

①.// strdup.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main()
{
char *s="Golden Global View";
char *d;
clrscr();
d=strdup(s);
if(NULL != d) {
printf("%s ",d);
free(d);
}
getchar();
return 0;
}
运行结果:
Golden Global View
②.Example:
CString sPath="d:\1.jpg";
LPTSTR str = strdup( sPath );
原文地址:https://www.cnblogs.com/the-tops/p/5891499.html