验证snprintf是否以null结尾
来源:互联网 发布:微信群加人软件免费版 编辑:程序博客网 时间:2024/05/18 02:45
昨天一个同事问我snprintf末尾是不是一定为'\0',我印象中以前看过strncpy不保证以'\0'结尾。今天早起感觉不妥,干脆试验一把。下面是结果。
测试代码
#include <stdio.h>int main(void){ char szBuf[10] = {0}; snprintf(szBuf, sizeof(szBuf), "1234567890"); printf(szBuf); printf("\n"); if (szBuf[9] == '\0') { printf("null end\n"); } return 0;}
环境一
SunOS solx55 5.10Generic_144489-17 i86pc i386 i86pc
结果
user%a.out
123456789
null end
man手册
The snprintf() function is identical tosprintf() with the
addition of the argument n, whichspecifies the size of the
buffer referred to by s. If n is 0, nothing is written and s
can be a nullpointer. Otherwise, output bytes beyond the
n-1st are discarded instead of being written to the array
and a null byte is written at theend of the bytes actually
written into the array.
环境二user%uname -a
Linux rhel65 2.6.32-131.0.15.el6.x86_64 #1SMP Tue May 10 15:42:40 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux
结果user%a.out
123456789
null end
管理员没有安装手册,所以没有man手册。环境三
user@ibm182 ~ $ uname-a
AIX ibm182 3 5 00033CE7D600
user@ibm182 ~ $ a.out
123456789
null end
man手册
The snprintf subroutine converts, formats,and stores the Value parameter values, under control of the Format parameter,into consecutive bytes, starting at the address specified by the Stringparameter. The snprintf subroutine places a null character (\0) at the end. Youmust ensure that enough storagespace is available to contain the formatted string. This subroutine providesconversion types to handle code points and wchar_t wide character codes. Thesnprintf subroutine is identical to the sprintf subroutine with the addition ofthe Number parameter, which statesthe size of the buffer referred to by the String parameter.
环境四user%uname -a
HP-UX hp12162 B.11.31 U ia64 0887221123 不限用户数的许可证
结果
user%a.out
123456789
null end
man手册
snprintf() behaves like sprintf(), exceptthat it limits the number of
characters written to the destination buffer to maxsize, including the
terminating null character.
很明显,四种环境都是以'\0'结尾,Windows平台就不测试了。
- 验证snprintf是否以null结尾
- C++string 类型结尾是否以'\0'结尾
- 判断文件是否有以.docx结尾
- 42、判断是否以元音字母结尾
- 判断是否以元音字母结尾
- C的strncpy和snprintf (是否补充最后字符串结尾)
- C的strncpy和snprintf (是否补充最后字符串结尾)
- 以***结尾
- 判断字符串是否以指定的字符串结尾
- 关于string类型的字符串是否以\0结尾
- 关于string类型的字符串是否以\0结尾
- NSString 检查一个字符串是否以另一个字符串结尾
- 关于string类型的字符串是否以\0结尾
- JS判断变量是否以某个字符串结尾
- 关于string类型的字符串是否以\0结尾
- 判断是否以指定的字符串开头或结尾
- 判断某个字符串是否以某个字符串开头或结尾
- 关于C++中String串是否以'\0'结尾
- 雷锋读图:平板电脑能否成为传统纸媒的救世主?
- cocos2d-x 开发网络游戏(http post&socket)
- 成为Android高手必须掌握的28大项内容和10个建议
- Linux下同步模式、异步模式、阻塞调用、非阻塞调用总结
- SQL Server HASH函数的妙用以及注意事项
- 验证snprintf是否以null结尾
- __user && address_space(1)
- 转载-关于加班的思考
- oracle 分页查询
- 分享几个jquery的效果,虽然有些很简单,但是可以学习学习编码
- 基于tcp开发—异步机制
- 在Eclipse下搭建Android开发环境教程
- HDFS Federation(联邦)
- 遇到猝死事件如何急救