问题描述
NULL保证评估''not true'',例如它是完全安全的吗?
便携可写:
char * pFoo = malloc(1024);
if(pFoo)
{
/ *使用pFoo
* /
免费(pFoo);
}
或者我必须明确检查NULL,如下所示:
if(pFoo!= NULL)...
谢谢。
-
- 马克 - >
-
AFAIK确实可以保证评估为不正确。一些C专家
可能会在这里提供更合格的意见。
-
/ - Joona Palaste(pa * ****@cc.helsinki.fi)--------------------------- \
| 飞翔的柠檬树中的金鸡王G ++ FR FW + M-#108 D + ADA N +++ |
| W ++ B OP + |
\ -----------------------------------------芬兰的规则! ------------ /
这不对。这甚至都不错。
- Wolfgang Pauli
便携式,但不安全,因为你没有检查
如果malloc()成功或失败。
我没有?如果(pFoo)那么以下是什么?我没有取消引用
pFoo直到检查之后是否(pFoo)。
如果失败,那么取消引用''pFoo''将给出undefined
行为。
如果''pFoo''不是== NULL,这将是真的。
不,你不必,但是许多程序员更愿意明确地与NULL明确地比较清楚。
我当然不是其中之一。我更喜欢C'的boolean。比较
显式值。谢谢你的回复。
-
- 马克 - >
-
Is NULL guaranteed to evaluate ''not true'', e.g. is it completely safe and
portable to write:
char *pFoo = malloc(1024);
if (pFoo)
{
/* use pFoo
*/
free(pFoo);
}
Or must I check against NULL explicitly as in:
if (pFoo != NULL) ...
Thanks.
--
- Mark ->
--
AFAIK it''s indeed guaranteed to evaluate as "not true". Some C expert
will probably offer a more qualified opinion here.
--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"This isn''t right. This isn''t even wrong."
- Wolfgang Pauli
No, you don''t have to, but many coders prefer to
explicitly compare against NULL in the interest
of clarity.
-Mike
Portable, but not safe, since you didn''t check
if malloc() succeeded or failed.
I didn''t? What''s the following if (pFoo) for then? I did not dereference
pFoo until after the check if (pFoo).
If it failed,
then a dereference of ''pFoo'' will give undefined
behavior.
This will be true if ''pFoo'' is not == NULL.
No, you don''t have to, but many coders prefer to
explicitly compare against NULL in the interest
of clarity.
I am certainly not one of them. I prefer C''s "boolean" comparisons to
explicit values. Thanks for the reply.
--
- Mark ->
--
这篇关于NULL:是否保证评估'not true'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!