snprintf()函数返回值“陷阱”
来源:互联网 发布:部落冲突升级数据大全 编辑:程序博客网 时间:2024/06/05 13:35
我最近优化一个Linux-C小程序,用snprintf()函数往数组(或字符串)里写入数据。我不用sprintf()是因为它不够安全,不小心就会内存溢出,导致“段错误”!我认识并使用snprintf()很久了,但今天才完全明白了它的返回值的意思。
函数原型:
int snprintf(char *str, size_t size, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
size 的作用就是限制往str写入不超过size个字节(包括了结尾的'\0')。
因为sprintf()函数如果成功的话,返回成功写入的字节数(字符数),我就一直以为snprintf()函数也是如此,也就是snprintf()函数不会返回大于size的整数。
看下面一段手册内容:
The functions snprintf() and vsnprintf() do not write more than size bytes (including the trailing ’\0’). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing ’\0’) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated.
如果输出因为size的限制而被截断,返回值将是“如果有足够空间存储,所应能输出的字符数(不包括字符串结尾的'\0')”,这个值和size相等或者比size大!也就是说,如果可以写入的字符串是"0123456789ABCDEF"共16位,但是size限制了是10,这样 snprintf() 的返回值将会是16 而不是10!
上面的内容还说,如果返回值等于或者大于size,则表明输出字符串被截断了(truncated)。
各位~注意啦~
原文地址:http://snailwarrior.blog.51cto.com/680306/152913
- snprintf()函数返回值“陷阱”
- snprintf()函数的返回值
- 有关snprintf返回值
- snprintf返回值的误解
- snprintf函数
- snprintf函数
- snprintf函数
- snprintf函数
- 函数 snprintf
- snprintf函数
- C++函数的返回值,你不懂得!陷阱无处不在!
- sprintf and snprintf的陷阱
- sprintf and snprintf的陷阱
- 函数返回值为指针的一个陷阱(使用inet_ntoa函数时遇到的问题)
- snprintf函数用法
- snprintf函数说明
- snprintf函数用法
- snprintf函数说明
- Project Euler 39
- JavaScript学习笔记(4)
- 常用正则表达式收集
- linux内核与驱动学习笔记(二)----对驱动简单的认识
- fill
- snprintf()函数返回值“陷阱”
- SQL基础(二)—— SELECT
- 程序员面试题精选100题(40)-扑克牌的顺子
- 【jQuery日期处理】两个时间大小的比较
- 2002 年9月19 --旧的日记
- Java乔晓松-连接池
- C/S 与 B/S 区别
- dropdownlist 显示指定选项
- 第五课 jaxws-webservice编程