IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    snprintf函数的返回值问题

    admin发表于 2014-03-11 11:16:53
    love 0

    平时在程序设计中,我们推荐使用snprintf, 主要是为了避免str写越界的情况发生,但是对snprintf的返回值理解有个误区,

    今天特别记录下。

    snprintf的函数原型为:

    int snprintf(char *str, size_t size, const char *format, …);

    说明:

    之前以为snprintf的返回值是实际写入到str字符串的长度,其实不然

    case 1 : 如果要输出的字符串的长度< size, 主要这里不包括=, 因为snprintf会自动将\0加入到str中,

    snprintf的返回值是实际str的长度

    case 2 : 如果要输出的字符串长度>= size, 则表明str的长度不够写入原有的长度,则snprintf的返回值

    在理想情况下(即str的长度足够长)的字符串长度,所以其返回值可能会出现>= size的情况。

    另外需要说明的snprintf会自动将’\0′追加到str的末尾,而snprintf的返回值是不包括’\0′的

    这个在官方的manual里写的比较清楚:

    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. (See also below under NOTES.)  If an output error is encountered, a negative value
    is returned.

    最多留言日志

    • 利用War-Ftpd的漏洞深入解析缓冲去溢出
    • 修改wordpress最新评论的显示样式
    • jquery ajax 提交checkbox数组的方法
    • 关于我
    • 程序员眼中的编程语言


沪ICP备19023445号-2号
友情链接