Definition of NULL

Andrew Brampton brampton+freebsd-hackers at
Sat May 2 16:52:41 UTC 2009

2009/5/2 Erik Trulsson <ertr1013 at>:
> On Sat, May 02, 2009 at 04:59:03PM +0100, 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.
> Is the use of C++ inside the kernel really supported?  I don't think so,
> but I could be wrong.

There are a few projects (other than mine) which uses C++ inside the
kernel, the biggest being the Click modular router.  So, with minimal
effort and no kernel patches it is easy to build a C++ kernel module,
thus I must assume it is supported even if it is unofficial. The
question of if C++ is sensible inside the kernel is left for another
day, and perhaps has been answered in numerous other freebsd-hackers@

>> >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).
> Not quite.  Any of those (as well as a whole bunch more) are legal
> definitions of NULL in C.  NULL is defined (in the C standard) to be a null
> pointer constant.  A null pointer constant is defined as a constant integer
> expression with value zero, or such an expression cast to (void*). (In C++
> it the cast to (void*) is not allowed.)
> This means that it would be perfectly legal (but of dubious utility) to have
> NULL defined as (5*5L+('1'-'0')-26) for example.
> The decision to define NULL as 0 or 0L or ((void*)0) is pretty much just a
> question of which buggy programs one wishes to break, or hide the bugs in.
> A correct C program should work regardless of which of those is used.

Thanks for the additional information.

>> 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?
> Perhaps to stop people from mistakenly using C++ inside the kernel?

The definition doesn't stop C++, it just generates additional warnings
and sometimes errors. I have avoided those warning by defining NULL
myself, however, I thought changing it in _null.h might help others,
even if you think they are mistakenly using C++.

> ...
> Erik Trulsson
> ertr1013 at

Thanks for your input.


More information about the freebsd-hackers mailing list