LWN.net Logo

The thorny case of kmalloc(0)

The thorny case of kmalloc(0)

Posted Jun 7, 2007 18:27 UTC (Thu) by pj (subscriber, #4506)
In reply to: The thorny case of kmalloc(0) by dvrabel
Parent article: The thorny case of kmalloc(0)

Exactly... it should be valid to allocate 0 bytes of memory as long as you don't try and dereference the pointer and use it for anything. Consider code like:

items[] itemblock = kmalloc( itemcount * sizeof(items) );

ASSERT(itemblock != NULL);

for(int i = 0; i++ ; i < itemcount) {

...do something with itemblock[i]...

}

itemcount is allowed to be 0 in the above code, with no problems. a kmalloc(0) occurs, but the for loop never gets its body run, so itemblock is never dereferenced. At the same time, the ASSERT only happens when there's a problem allocating memory.

It's a good solution. And I like Linus' comment :)


(Log in to post comments)

The thorny case of kmalloc(0)

Posted Jun 8, 2007 16:05 UTC (Fri) by giraffedata (subscriber, #1954) [Link]

the ASSERT only happens when ...

Grrr. The ASSERT always "happens" -- it's right there in unconditional code. The assertion fails only when ...

And really, it shouldn't even be discussed. If you're asserting that the pointer is not null, that means you're assuming for simplicity that the the allocation didn't fail and if you discuss the possibility that it did fail, you've defeated the purpose of the assertion. This code should probaby be instead an explicit test of the pointer for NULL.

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds