c++ - sprintf_s 如何避免缓冲区溢出问题

标签 c++ windows visual-studio

Visual Studio 提示我将 sprintf 替换为 sprintf_s,而不是 snprintf

sprintf_s 不需要长度参数,它如何避免缓冲区溢出问题?

最佳答案

有两个版本。一种模板版本尝试推断缓冲区的大小,另一种模板版本用于传递大小。

int sprintf_s<_Size>(char (&_Dest)[_Size], const char *_Format, ...)
int sprintf_s(char * _DestBuf, size_t _SizeInBytes, const char *_Format, ...)

如果第一个推不出来,就得自己传size

所以这样:

char buf[100];

sprintf_s(buf, "%d", 1);

会实例化一个函数模板

sprintf_s<100>();

这将产生一个编译器错误:

char *buf = new char[100];

sprintf_s(buf, "%", 1);

而且你必须使用其他版本才能编译:

sprintf_s(buf, 100, "%d", 1);

关于c++ - sprintf_s 如何避免缓冲区溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68313132/

相关文章:

c++ - 查找 cv::Mat 的最大值

c++ - 100 万数组中的 C/C++ Stackoverflow 错误

c++ - 从列表中删除特定对象 (c++)

c++ - libjpeg 可以用来改变 C++ 中图像的对比度吗?

python - 将TensorFlow Faster R-CNN卡住图转换为Intel OpenVINO框架时发生内部错误

visual-studio - 使用 Visual Studio 2019 构建但越来越依赖 MFC140U.dll

c# - Windows 10(现代)通用应用程序平台(UWP)消息框

Python file.write 创建额外的回车

visual-studio - PowerBuilder 12 与 Visual Studio - 设计师支持

visual-studio - Visual Studio 2012 启动时无响应,并显示隐藏的错误消息(启动时有两个 clang )