免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: cpu0018
打印 上一主题 下一主题

[C] 为什么下面 code 会 crash ? [复制链接]

论坛徽章:
9
摩羯座
日期:2013-08-15 15:18:48狮子座
日期:2013-09-12 18:07:47金牛座
日期:2013-09-16 13:23:09辰龙
日期:2013-10-09 09:03:27白羊座
日期:2013-10-17 13:32:44子鼠
日期:2014-04-23 15:09:38戌狗
日期:2014-09-17 11:37:542015年亚洲杯之韩国
日期:2015-03-26 10:16:442015亚冠之武里南联
日期:2015-08-18 14:55:52
11 [报告]
发表于 2013-08-15 15:15 |只看该作者
本帖最后由 w_anthony 于 2013-08-15 15:17 编辑

回复 9# hellioncu


编辑掉,不好意思,是我看漏了

论坛徽章:
4
水瓶座
日期:2013-09-06 12:27:30摩羯座
日期:2013-09-28 14:07:46处女座
日期:2013-10-24 14:25:01酉鸡
日期:2014-04-07 11:54:15
12 [报告]
发表于 2013-08-15 16:53 |只看该作者
strncpy经常有人用错, 因为有一种情况是不会\0结尾的, 解释如下:
  1.        The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.  The
  2.        strings may not overlap, and the destination string dest must be large enough to receive the copy.  Beware of buffer overruns!  (See BUGS.)

  3.        The strncpy() function is similar, except that at most n bytes of src are copied.  Warning: If there is no null byte among the first n  bytes
  4.        of src, the string placed in dest will not be null-terminated.

  5.        If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are written.

  6.        A simple implementation of strncpy() might be:

  7.            char *
  8.            strncpy(char *dest, const char *src, size_t n)
  9.            {
  10.                size_t i;

  11.                for (i = 0; i < n && src[i] != '\0'; i++)
  12.                    dest[i] = src[i];
  13.                for ( ; i < n; i++)
  14.                    dest[i] = '\0';

  15.                return dest;
  16.            }
复制代码

论坛徽章:
0
13 [报告]
发表于 2013-08-15 17:57 |只看该作者
strncpy在拷贝结束后,还要把dst剩余的空间都清零导致

为什么清零就到这了Segmental fault
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP