C++你所不知道的sprintf_s与sprintf的不同

sprintf_s 与sprintf的不同只是缓冲区的大小进行了安全处理吗?

 NO!

int sprintf_s(
char *buffer,
size_t sizeOfBuffer,
const char *format [,
argument] ...
);
int sprintf(
char *buffer,
const char *format [,
argument] ...
);
微软的技术文档中对于他们的不同有如下描述:
One main difference between sprintf_s and sprintf is that sprintf_s checks the format string for valid formatting characters, whereas sprintf only checks if the format string or buffer are NULL pointers. If either check fails, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, the function returns -1 and sets errno to EINVAL.
The other main difference between sprintf_s and sprintf is that sprintf_s takes a length parameter specifying the size of the output buffer in characters. If the buffer is too small for the text being printed then the buffer is set to an empty string and the invalid parameter handler is invoked. Unlike snprintf,sprintf_s guarantees that the buffer will be null-terminated (unless the buffer size is zero).
说的是,sprintf_s和sprintf的主要不同是sprintf_s对于格式化string中的格式化的字符的有效性进行了检查,而sprintf仅仅检查格式化string或者缓冲区是否是空指针。如果有错误则返回相应的错误代码。
另一个不同,sprintf_s也携带着接收格式化字符串的缓冲区的大小。如果,格式化字符串过大,则sprintf_s会返回一个空string和设置无效参数句柄为激活。与snprintf不同,sprintf_s不会保证缓冲区为以null结尾,除非,缓冲区的大小为0。

真的没有别的不同了吗?

 答案是否定的,sprintf_s将格式化字符串存到缓冲区,并在下一个位置填充Null后将格式化字符串未占用的缓冲区(Null之后的Buffer)全部填充为-3,而sprintf却不会填充而是保持缓冲区中未占用的存储位置上的数据。
如下代码:
	char State1[50]="ABCDE";
	char State2[50]="ABCDE";
	string strTest("Flag");
	sprintf_s(State1,sizeof(State1),"%s",strTest.c_str());
	sprintf(State2,"%s",strTest.c_str());
执行 结果如下:









版权声明:本文为Nancy_m原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。