c++里printf和printf_s有什么区别?
有时候会警告不安全
6条回答 默认 最新
战在春秋 2017-06-18 21:40关注简单的说,printf_s的安全性更强。
引自: msdn(printf_s)
The main difference between printf_s and printf is that printf_s checks the format string for valid formatting characters, whereas printf only checks if the format string is a null pointer.
主要区别就在于printf只会检查格式字符串是否为空(null),而printf_s还会检查格式字符串是否合法。
一个例子:
char* value = "Hello world!"; char* formatStr = "%s%d%h\n"; printf(formatStr, test,10); // 可以输出“Hello world!10” printf_s(formatStr, test, 10); //会报错实际上,以上只是一个比较简单的例子,当出现以下情况时,printf_s也会报错。
- the conversion specifier %n is present in format
- any of the arguments corresponding to %s is a null pointer
- format or buffer is a null pointer
- bufsz is zero or greater than RSIZE_MAX
- encoding errors occur in any of string and character conversion specifiers
有兴趣的话,可以深入研究,如果只是使用的话,按照函数原型说明调用printf_s就行。
自c++11后,微软推荐使用更安全的printf_s,所以编译会提醒。用心回答每个问题,如果对您有帮助,请采纳答案好吗,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 14无用 1