阿杰,我给你整理一份 strdup
函数详解,包括概念、用法、返回值、注意事项和示例。
char *strdup(const char *s);
s
并在堆上分配新内存,返回新字符串的指针。#include <string.h>
#include <stdlib.h> // 部分系统需要
NULL
(内存不足)\0
)分配内存等价于:
char *strdup(const char *s) {
size_t len = strlen(s) + 1;
char *p = malloc(len);
if (p) {
memcpy(p, s, len);
}
return p;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
const char *original = "Hello, AJie!";
char *copy = strdup(original); // 复制字符串
if (copy == NULL) {
printf("内存分配失败\n");
return 1;
}
printf("原字符串: %s\n", original);
printf("复制字符串: %s\n", copy);
free(copy); // 注意释放内存
return 0;
}
输出:
原字符串: Hello, AJie!
复制字符串: Hello, AJie!
strdup
在堆上分配内存,需要 手动释放(free()
)。strdup
_strdup()
NULL
会导致未定义行为strdup
自动分配内存并复制字符串free()
释放内存_strdup()
malloc + strcpy
https://www.52runoob.com/archives/7363
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。