[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.4.2 (lua_newstate)
- From: Roberto Ierusalimschy <roberto@...>
- Date: Tue, 10 Nov 2020 10:41:53 -0300
> Ok, Makes sense to not use 0.
> In fact, I never use 0 with pointers, but I've seen a lot of code like this.
> Including IUP Lua.
> Why not memset with (int) NULL, wouldn't work?
The reality according to ISO C is subtle. 0 *is* the null pointer,
when it is a constant properly converted to a pointer:
6.3.2.3 Pointers
[...]
3 An integer constant expression with the value 0, or such an
expression cast to type void *, is called a null pointer constant.(55)
If a null pointer constant is converted to a pointer type, the
resulting pointer, called a null pointer, is guaranteed to compare
unequal to a pointer to any object or function.
(55) The macro NULL is defined in <stddef.h> (and other headers) as
a null pointer constant; see 7.17.
So, the "official" NULL in C is actually 0, NULL is only a macro.
The subtlelty is the cast: A null pointer is *a null pointer constant
converted to a pointer type*. A 0 converted to a float does not have
a zero representation; similarly, a constant 0 converted to a pointer
may not have a zero representation. And only a constant 0 converted
to a pointer is guaranteed to be NULL.
memset "fill[s] memory with a constant byte", not with a constant
pointer. So, the 0 (or NULL) given to it will never be a pointer,
and cannot properly represent the NULL pointer in an arbitrary
arquitecture, only in arquitectures where NULL is represented by
the same byte repeated multiple times. (In an 64-bit arquitecture
where the NULL is represented internally as 0xABABABABABABABAB,
«memset(m, 0xAB, len)» will initialize m with NULLs :-).
BTW, note that NULL is a "null pointer constant", not a "null
pointer" :-)
-- Roberto