Re: [RFC] [PATCH] cpuset operations causes Badness at mm/slab.c:777 warning

Linus Torvalds
2007-06-01T23:00:54Z

On Fri, 1 Jun 2007, Christoph Lameter wrote:
>
> Right it could catch a lot of other bugs as well.

I'd actually prefer "malloc(0)" to _not_ return NULL, but some known
(non-NULL) bogus pointer.

Why?

Because it's quite sane to have simple logic like

ptr = malloc(size);
if (!ptr)
return -ENOMEM;

and writing it as

if (size && !ptr)
return -ENOMEM;

is just annoying.

Also, NULL is _special_. There are absolutely tons of code in the kernel
(and elsewhere) that just does something *different* from NULL pointers,
and that totally breaks the whole notion of "you can allocate a zero-sized
allocation, you just must not dereference it". If people special-case
NULL as something else, they won't even go through the normal code-path.

So for *both* of the above reasons, it's actually stupid to return NULL
for a zero-sized allocation. It would be much better to return another
pointer that will trap on access. A good candidate might be to return

#define BADPTR ((void *)16)

which is a portable-enough (where "portable-enough" is "against strict
ANSI C rules, but works in practice on all architectures") way to return
something that will cause the same page fault behaviour as NULL, but will
_not_ trigger the "NULL is special" code.

(Of course, you then need to teach "kfree()" to accept it as another
pointer to be ignored, that's fine).

I bet you'd find *more* problems that way than by returning NULL, and
you'd also avoid the whole problem with "if (!ptr) return -ENOMEM".

Linus