gpt4 book ai didi

c - 在跨平台应用程序中使用 snprintf

转载 作者:太空狗 更新时间:2023-10-29 16:51:45 24 4
gpt4 key购买 nike

我正在编写一个 C 程序,预计可以使用所有主要编译器进行编译。目前我正在 linux 机器上的 GCC 上开发,将在提交代码之前在 MSVC 上编译。为了简化交叉编译,我使用 -ansi-pedantic 标志进行编译。在我开始使用 C89 标准中不可用的 snprintf 之前,这一直很有效。 GCC 可以在没有 -ansi 开关的情况下编译它,但是 MSVC 总是会失败,因为它不支持 C99。

所以我做了类似的事情,

#ifdef WIN32 
#define snprintf sprintf_s
#endif

这很有效,因为 snprintfsprintf_s 具有相同的签名。我想知道这是正确的方法吗?

最佳答案

我找到了 this关于使用 _snprintf() 作为替代方案,以及缓冲区溢出保护实际触发时涉及的问题。从我快速浏览的内容来看,类似的警告适用于 sprintf_s

Can you see the problem? In the Linux version, the output is always null-terminated. In MSVC, it's not.

Even more subtle is the difference between the size parameter in Linux and count parameter in MSVC. The former is the size of the output buffer including the terminating null and the latter is the maximum count of characters to store, which excludes the terminating null.

哦,别忘了给微软发邮件,要求他们支持当前的语言标准。 (我知道他们已经宣布他们没有支持 C99 的计划,但无论如何都要打扰他们。他们活该。)

底线,如果你想真正安全地玩它,你必须提供你自己的 snprintf() (_snprintf()sprintf_s() 捕获它们的非标准行为)用于 MSVC。

关于c - 在跨平台应用程序中使用 snprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com