Definition of NULL

John Baldwin jhb at
Mon May 4 19:22:23 UTC 2009

On Saturday 02 May 2009 11:59:03 am Andrew Brampton wrote:
> I'm writing a C++ Kernel Module, and one thing that has been bugging
> me is the kernel's definition of NULL.
> sys/sys/_null.h (in CURRENT):
> #if defined(_KERNEL) || !defined(__cplusplus)
> #define NULL    ((void *)0)
> #else
> #if defined(__GNUG__) && defined(__GNUC__) && __GNUC__ >= 4
> #define NULL    __null
> #else
> #if defined(__LP64__)
> #define NULL    (0L)
> #else
> #define NULL    0
> #endif  /* __LP64__ */
> #endif  /* __GNUG__ */
> #endif  /* _KERNEL || !__cplusplus */
> >From what I've read online the definition of NULL in C is (void *)0,
> whereas in C++ it should be 0, or 0L (on 64bit machines).
> Now, my C++ kernel module is built with _KERNEL definited, like any
> other C kernel module. This leads to NULL being defined incorrectly.
> So I have a question and two suggestions. Firstly, why is the #if
> defined(_KERNEL) in _null.h? Is it to stop userland application
> applications picking up this definition? Or for another reason?

Yes.  NULL used to be 0.  When it was changed to '(void *)0' I believe it 
broke several applications in ports.  As a compromise, NULL was restored back 
to 0 in userland and only set to '(void *)0' in the kernel.
> and two, how about we change the first line of _null.h so that we use
> a && instead of a || like so:
> #if defined(_KERNEL) && !defined(__cplusplus)

I think this would be ok to let C++ work in the kernel.  "Embedded" C++ (no
exceptions and no dynamic_cast<>) should work fine in theory.  I would not
change the value of NULL that userland sees though as I think that may be too

John Baldwin

More information about the freebsd-hackers mailing list