关于法律论点的几个问题的printf("%S&QUOT,...) [英] A few questions about legal arguments to printf("%s", ...)

查看:178
本文介绍了关于法律论点的几个问题的printf("%S&QUOT,...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个修改printf的实施,我不知道对这些问题的答案。


  1. 请问零工作作为一个空字符串? (为的printf(%S,0)允许?)

    我猜没有,因为0是一个 INT 。但后来这提示了这个问题:


  2. 确实 NULL 工作作为一个空字符串? (IS 的printf(%S,NULL)允许?)

    从逻辑上讲,我觉得应该是肯定的,因为 NULL 意味着一个指针;但很多实现似乎的#define NULL 0 ,所以我觉得在实践中它可能是否定的。哪个是正确的?


  3. 请问指针类型的有无的指向字符? (为的printf(%S(无效常量*))允许?)

    我的猜测是该类型并不重要,但我不知道。



解决方案

第1种情况是不确定的行为,因为参数的类型( INT )不匹配需要的类型由格式说明符(的char * )。

案例二是出于同样的原因未定义的行为。 NULL 允许被定义为任何整型常量前pression值为0,或者这样一个前pression投地(无效*)。这些类型都不是的char * ,这样的行为是不确定的。

案例三是出于同样的原因未定义的行为。 产生一个有效的指针null结尾的字符数组(字符串),但是当你将它转换为常量无效* ,它不再有正确的类型相匹配的格式字符串。这样的行为是不确定的。

I'm creating a modified printf implementation, and I'm not sure about the answers to these questions.

  1. Does zero work as a null string? (Is printf("%s", 0) allowed?)

    I'm guessing no, because 0 is an int. But then this prompts this question:

  2. Does NULL work as a null string? (Is printf("%s", NULL) allowed?)

    Logically, I think it should be yes, because NULL implies a pointer; but a lot of implementations seem to have #define NULL 0, so I feel in practice it might be no. Which is correct?

  3. Does the pointer type have to point to char? (Is printf("%s", (void const *)"") allowed?)

    My guess is that the type doesn't matter, but I'm not sure.

解决方案

Case 1 is undefined behavior because the type of the argument (int) does not match the type required by the format specifier (char *).

Case 2 is undefined behavior for the same reason. NULL is allowed to be defined as any integer constant expression with value 0, or such an expression cast to (void *). None of these types are char *, so the behavior is undefined.

Case 3 is undefined behavior for the same reason. "" yields a valid pointer to a null-terminated character array (string), but when you cast it to const void *, it no longer has the right type to match the format string. Thus the behavior is undefined.

这篇关于关于法律论点的几个问题的printf("%S&QUOT,...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆