(standard c libraries translation )strdup

strdup, strndup, strdupa, strndupa - duplicate a string
strdup, strndup, strdupa, strndupa -复制一个字符串

所需头文件
#include <string.h>

char *strdup(const char *s);
char *strndup(const char *s, size_t n);
char *strdupa(const char *s);
char *strndupa(const char *s, size_t n);

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).
strdup函数返回一个指向字符串s的副本字符串的指针,新字符串的内存是通过malloc分配的,可以用free来释放。

The strndup() function is similar, but only copies at most n bytes.  If s is longer than n, only n bytes are copied, and a terminating null byte ('\0') is added.
strndup类似,但是最多复制n个字节,如果字符串s大于n个字节,那么最多复制n个字节,然后加上一个字符串结束符\0

strdupa()  and strndupa() are similar, but use alloca(3) to allocate the buffer.  They are only available when using the GNU GCC suite, and suffer from the same limitations described in alloca(3).
strdupa和strndupa类似,但是使用alloca来分配内存,他们仅仅在GUN GCC环境中可供使用,同时必须忍受alloca带来的限制

The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.
strdup函数返回指向副本字符串的指针,当没有足够的内存的时候返回NULL


ENOMEM Insufficient memory available to allocate duplicate string.
当没有足够的内存分配给字符串副本的时候返回ENOMEM


testcase如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
	const char *src = "hello world!";
	char *dest = NULL;

	dest = strdup(src);
	printf("dest = %s\n", dest);
	free(dest);

	dest = strndup(src, 10);
	printf("dest = %s\n", dest);
	return 0;
}

运行结果如下:

cheny.le@cheny-ThinkPad-T420:~/cheny/testCode$ ./a.out
dest = hello world!
dest = hello worl

可以看到第二个结果复制了11字节的字符串(10个字节的数据,还有一个字节的字符串结束符),跟前面的

”only 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所返回指针指向的内存是由malloc分配的,所以在用完的时候需要free掉的,不然会有内存泄露哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值