我将项目中的sprintf换成sprintf_s,以为这样的话程序在字符串格式化时就安全了,结果在实际环境中程序还是崩溃了,百思不得其解。
自己在VS中尝试了这样的代码:
char buf[5] = { 0 };
const char *p = "123456";
sprintf_s(buf, 5, "%s", pp);
本以为是buf中应该是1234,实际上不是这样的,程序直接就崩溃掉了。
查询MSDN才知道:
sprintf_s takes a length parameter specifying the size of the output
buffer in characters. If the buffer is too small for the formatted
text, including the terminating null, then the buffer is set to an
empty string by placing a null character at buffer[0], and the invalid
parameter handler is invoked. Unlike _snprintf,
译文:sprintf_s使用一个长度参数指定(以字符为单位的)输出buffer的大小。如果buffer(包括结束符null)太小,则通过设置buffer[0]为null字符将buffer设置为空字符串,并调用无效参数处理程序。与_snprintf不同。
就是说使用sprintf_s,如果buffer(包括结束符null)太小,会调用无效参数处理程序,需要使用_snprintf_s来代替sprintf_s
char buf[5] = { 0 };
const char *pp = "123456";
_snprintf_s(buf, 5, _TRUNCATE, "aa:%s", pp);