Re: Simulation of Sizeof operator



pete wrote:
>
> Flash Gordon wrote:
> >
> > kaikai wrote:
> > > Flash Gordon wrote:
> > >
> > >>zikaizhang@xxxxxxxxx wrote:
> > >>
> > >>>since NULL may not be 0, why not try this?
>
> NULL may be zero.
>
> > >>>#define Sizeof(type) ((char *)((type*)NULL + 1) - NULL)
> > >>
> > >>Pointer arithmetic is only defined for pointers
> > >>that point to an object
> > >>null pointers do not point to objects.
> > >>So this is invokes undefined and anything could happen.
>
> Undefined behavior, yes.
>
> > > I think pointer arithmetic is performed at compile time,
> > > so I guess if
> > > the compiler knows the type it may do that.
> >
> > The compiler *might* do it at compilation time, but it is under no
> > obligation to do that.
>
> It's "constant expressions" which the compiler has the option
> to calculate during compile time.
>
> There's nothing special about pointer arithmetic,
> a far as compile time vs. run time issues are concerned.
>
> > > Do you mean some compilers
> > > will check the object and refuse to do pointer arithmetic when the
> > > object is invalid?
> >
> > A processor might trap at run time when an
> > invalid address is loaded in to a pointer variable.
>
> I'm not following.
> There's neither objects nor variables in that Sizeof() macro.
>
> (type*)NULL is a null pointer.

.... which is also a constant expresssion.

N869
6.6 Constant expressions
[#9] An address constant is a null pointer, a pointer to an
lvalue designating an object of static storage duration, or
to a function designator;

> (null pointer + 1) is undefined: it's just that simple.
>
> N869
> 7.17 Common definitions <stddef.h>
> [#3] The macros are
> NULL
> which expands to an implementation-defined null pointer
> constant
>
> 6.3.2.3 Pointers
> [#3] 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.
>
> 6.5.6 Additive operators
> [#8] If both the
> pointer operand and the result point to elements of the same
> array object, or one past the last element of the array
> object, the evaluation shall not produce an overflow;
> otherwise, the behavior is undefined.

--
pete
.



Relevant Pages