如果我执行 printf(“one\0two”); 会发生什么?
正如标题所暗示的,如果我在 C++ 中执行此操作,将打印什么:
printf("one\0two");
?当我这样做时,GCC 会发出警告,但 Visual Studio 对此没有意见。他们的工作方式有什么不同吗?考虑一下,我希望 printf 在第一个 \0 处停止,但显然使用它的代码到目前为止一直在 Windows 上运行良好,所以我不确定。
As implied by the title, what's meant to get printed if I do this in C++:
printf("one\0two");
? GCC gives me a warning when I do this, but visual studio is fine with it. Do they work differently at all? Thinking about it, I'd expect printf to stop at the first \0, but apparently the code that uses this has been working fine on windows until now, so I'm not sure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将得到:
\0
是 null 并结束字符串。没有换行符。You'll get:
the
\0
is a null and ends the string. No newline.C 样式字符串以 null 结尾。因此,在打印字符串时,它将打印直到第一次出现空字符为止的所有内容。在这种情况下,它应该打印
one
而没有其他内容。C-style strings are null terminated. So when printing a string, it will print everything up to the first occurrence of a null character. In that case, it should print
one
and nothing else.你会得到“one”打印 - 后面没有换行符。
您还会收到编译器警告。
GCC 很友善——让你知道“两个”是无关紧要的。
您也不应该使用将printf()
与没有%
标记的格式字符串一起使用没有什么意义...您可以请改用puts()
或fputs()
。出于安全原因,不要使用用户可以选择的格式字符串,这一点至关重要:char *s = ...; printf(s);
.MSVS 没有向您发出警告并没有错;编译器没有义务建议修复代码的方法。
You get 'one' printed - with no newline after it.
You also get compiler warnings.
GCC is being kind - letting you know that the 'two' is irrelevant.
You also should not useThere is little point in usingprintf()
with a format string with no%
marks in it...you could useputs()
orfputs()
instead. And it is crucial for security reasons not to use a format string that the user can choose:char *s = ...; printf(s);
.MSVS is not wrong in not giving you the warning; the compiler is not obliged to suggest ways to fix your code.
printf
确实会停在嵌入的“null”字符处,只打印“one”。GCC 会发出警告,因为这样的格式字符串很可能是错误的;它还会将格式字符串与参数类型进行比较,如果不匹配则发出警告。其他编译器不会花太多精力来分析 printf 等函数的参数,并且会让不可靠的参数通过而不发出警告。
printf
will indeed stop at the embedded "null" character, and just print "one".GCC gives a warning, because there's a good chance that a format string like this is wrong; it will also compare the format string with the argument types and give warnings if they don't match. Other compilers don't put so much effort into analysing the arguments of functions like
printf
and will let dodgy arguments through with no warnings.