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\n",d);
free(d);
}
getchar();
return 0;
}
运行结果:
Golden Global View
②.Example:
CString sPath="d:\\1.jpg";
LPTSTR str = strdup( sPath );
posted @   the_tops  阅读(8536)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示