C中字符串的库函数strncpy没有以NULL结尾

对于长度受限的字符串函数 strncpy strncat
strncat在结尾字符串后面添加一个NULL,而strncpy却没有
为什么会这样,明显strncpy添加一个NULL会预防溢出,函数的鲁棒性会提高,并且也没什么坏处

阅读 4.2k
1 个回答

C库有很多实现,不同平台/工具都有自己的实现
strncpy 函数的实现已经成了标准,如果新库实现跟以往不一样,
会使用户疑惑(加0使得实际拷贝字符数可能为n-1,与预期不符)!
而且有时候利用strncpy的非0结束特性来连接数组
——不建议这样用,但并不是没人这样用,特别是老的开源库

至于历史原因:

The strncpy() function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进