strdup
来自cppreference.com
| 在标头 <string.h> 定义
|
||
| |
(C23 起) | |
返回指向作为 src 所指向的字符串的副本的空终止字节字符串的指针。如同通过调用 malloc 获得新字符串的空间。必须将返回的指针传递给 free 以避免内存泄漏。
若出现错误,则返回空指针值并可能设置 errno。
参数
| src | - | 指向要复制的空终止字节字符串的指针 |
返回值
指向新分配的字符串的指针,或若出现错误则为空指针值。
注解
该函数等同于 POSIX strdup 。
示例
运行此代码
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *s1 = "Duplicate me!";
char *s2 = strdup(s1);
printf("s2 = \"%s\"\n", s2);
free(s2);
}
输出:
s2 = "Duplicate me!"
参阅
(C23) |
分配拥有指定大小的字符串副本 (函数) |
(C11) |
复制字符串给另一个 (函数) |
| 分配内存 (函数) | |
| 归还之前分配的内存 (函数) |