丢人的strncpy 语义理解错误

今天发现strncpy使用上的一个古怪bug, 解决了是发现对strncpy的语义理解错误。

SYNOPSIS
#include <string.h>

char *strcpy(char *dest, const char *src);

char *strncpy(char *dest, const char *src, size_t n);

DESCRIPTION
The strcpy() function copies the string pointed to by src (including
the terminating '\0' character) to the array pointed to by dest. The
strings may not overlap, and the destination string dest must be large
enough to receive the copy.

The strncpy() function is similar, except that not more than n bytes of
src are copied. Thus, if there is no null byte among the first n bytes
of src, the result will not be null-terminated.

[color=red]In the case where the length of src is less than that of n, the remain-
der of dest will be padded with null bytes.[/color]


请非常注意上面的红字:
1. 低效率的padding 因为常规情况下buffer要比实际的字符串大的多,所以无辜的填充。
2. 一旦不小心你的n 比 buffer的长度大 那就死惨了 内存狂越界写。
这种情况经常发生在你把buffer的长度改小了 但是后面的n没有相应地改。

相信很多人会遭受这个使用bug.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值