将空指针提供给snprintf时的预期行为 [英] Expected behaviour when null pointer given to snprintf
问题描述
此代码段的预期行为是什么?
What is the expected behaviour for this code snippet?
char * aNullPointer = 0;
snprintf (res, 128, "Testing %s null pointer",aNullPointer);
请注意,我正在故意使它取消引用空指针aNullPointer
.
Note that I am deliberately trying to get it to de-reference my null pointer aNullPointer
.
行为1)res
指向字符串测试(空)空指针"
Behaviour 1) res
points to a string "Testing (null) null pointer"
行为2)段故障
根据我的平台,我似乎有不同的行为.有些snprintf
实现执行健全性检查,而其他的则没有.
It seems I get differing behaviours depending on my platform. Some snprintf
implementations perform a sanity check, whereas others do not.
最常见的行为是什么?
推荐答案
这是未定义的行为-没什么可期待的.某些实现会检查NULL
并将其替换为"nil"或"null"的事实只是一个很好的事实,您根本不能依赖它.
It's undefined behavior - there's nothing to expect. The fact that some implementations check for NULL
and replace it with "nil" or "null" is just a nicety, you can't rely on it at all.
这篇关于将空指针提供给snprintf时的预期行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!