小心strncpy!

 

【问题描述】

在Linux-2.6.23中strncpy的函数原型如下:

Linux-2.6.23/lib/string.h(line110-134) /** * strncpy - Copy a length-limited, %NUL-terminated string * @dest: Where to copy the string to * @src: Where to copy the string from * @count: The maximum number of bytes to copy * * The result is not %NUL-terminated if the source exceeds * @count bytes. * * In the case where the length of @src is less than that of * count, the remainder of @dest will be padded with %NUL. * */ char *strncpy(char *dest, const char *src, size_t count) { char *tmp = dest; while (count) { if ((*tmp = *src) != 0) src++; tmp++; count--; } return dest; }

(1) 为什么要使用*tmp?

(2)

if ((*tmp = *src) != 0) src++; tmp++;

为什么不写成:

if ((*tmp++ = *src++) != 0) ;

(3) 使用strncpy该注意些什么?

 

【解析】

(1) 为什么要使用*tmp?

这样返回的指针是指向起始地址。

(2)

如果将

if ((*tmp = *src) != 0) src++; tmp++;

改写成:

if ((*tmp++ = *src++) != 0) ;

试想一下,如果src的长度小于count会发生什么?

当src的长度大于等于count时,不会出现什么问题。当src的长度小于count时,src会继续执行*src++,指针指向超出了src的地址范围,其结果是未知的。

(3)

当src的长度小于count时,dest会添加NUL('\0')字符。当src的长度大于或等于count,dest就不会添加NUL,这样就不符合字符串的定义。因此,程序设置的count值要比dest的大小至少小1,这样就可以将空字符放在数组的最后一个元素里,例如:

strncpy(dest,src,TAGSIZE-1); dest[TAGSIZE-1] = '\0';

其中TAGSIZE是dest的大小。

 


 

 


 

 

转载于:https://www.cnblogs.com/J2EEPLUS/archive/2012/03/11/2487953.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值