Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6078428
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类: C/C++

2013-10-17 09:00:35

原文地址:诡异的snprintf() 作者:mfc42d

以前使用snprintf()不是一年两年了,以前经常写
snprintf(params->ipsubnet,IP_MASK,"%s/%d",g_sslvpnconfig.serverip,slash);
params->ipsubnet[IP_MASK-1]='\0';

最近在做nginx模块时发现了问题,snprintf格式化字符串时,自动少了一位。
man了一下,The functions snprintf() and vsnprintf() write at most size bytes (including the trailing null byte ('\0')) to str.
我记得vs2005,不会自动添加'\0'
#include
#include

int main (void)
{
    char buffer[2];

    snprintf(buffer, sizeof(buffer), "SomeString");

    return 0;
}
vs2010没有snprintf函数,提供了_snprintf,因为snprintf是c99的一部分,微软没有支持c99,转而支持c++11,snprintf是c++11的一部分。
#ifdef _MSC_VER

#define snprintf c99_snprintf

inline int c99_snprintf(char* str, size_t size, const char* format, ...)
{
    int count;
    va_list ap;

    va_start(ap, format);
    count = c99_vsnprintf(str, size, format, ap);
    va_end(ap);

    return count;
}

inline int c99_vsnprintf(char* str, size_t size, const char* format, va_list ap)
{
    int count = -1;

    if (size != 0)
        count = _vsnprintf_s(str, size, _TRUNCATE, format, ap);
    if (count == -1)
        count = _vscprintf(format, ap);

    return count;
}

#endif // _MSC_VER

阅读(1322) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~