background image

7,

 

可以定义自己的 NULL 的实现吗?兼答"NULL 

 

的值可以是 1、2、3 等值吗?"类

似问题

[7.1.3-2] If the program declares or defines an identifier in a context in 
which it is reserved (other than as allowed by 7.1.4), or defines a reserved 
identifier as a macro name, the behavior is undefined.

NULL 

 

是标准库中的一个符合上述条件的 reserved identifier (保留标识符)。所

 

以,如果包含了相应的标准头文件而引入了 NULL 的话,则再在程序中重新定义 
NULL 为不同的内容是非法的,其行为是未定义的。也就是说,如果是符合标准的程

 

序,其 NULL 

 

的值只能是 0

 

,不可能是除 0 

 

之外的其它值,比如 1、2、3 等。

8,malloc 

 

函数在分配内存失败时返回 0 

 

还是 NULL?

malloc 

 

函数是标准 C 规定的库函数。在标准中明确规定了在其内存分配失败时返回

 “

的是一个 null pointer”(空指针):

[7.20.3-1] If the space cannot be allocated, a null pointer is returned.

 

对于空指针值,一般的文档(比如 man

 

)中倾向于用 NULL 表示,而没有直接说成 

0

 

。但是我们应该清楚:对于指针类型来说,返回 NULL   

 

和 返回 0 是完全等价的,

 

因为 NULL   

和 0 

 “

都表示 null pointer”(空指针)。(tyc:一般系统中手册中都返

回 NULL,那我们就用 NULL

 

吧)

另外,附 C FAQ 上关于 null pointer 的解释:C FAQ:null pointer