关于法律论点的几个问题的printf("%S&QUOT,...) [英] A few questions about legal arguments to printf("%s", ...)
问题描述
我创建一个修改printf的实施,我不知道对这些问题的答案。
-
请问零工作作为一个空字符串? (为
的printf(%S,0)
允许?)我猜没有,因为0是一个
INT
。但后来这提示了这个问题: -
确实
NULL
工作作为一个空字符串? (IS的printf(%S,NULL)
允许?)从逻辑上讲,我觉得应该是肯定的,因为
NULL
意味着一个指针;但很多实现似乎的#define NULL 0
,所以我觉得在实践中它可能是否定的。哪个是正确的? -
请问指针类型的有无的指向
字符
? (为的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.
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:Does
NULL
work as a null string? (Isprintf("%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?Does the pointer type have to point to
char
? (Isprintf("%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屋!