验证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平台就不测试了。