Re: [PATCH v9 8/9] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
From: Gary Guo
Date: Thu Oct 08 2026 - 12:04:26 EST
On Thu Oct 8, 2026 at 4:47 PM BST, Yury Norov wrote:
> On Thu, Oct 01, 2026 at 03:20:40PM +0900, Alexandre Courbot wrote:
>> On Wed Sep 30, 2026 at 2:05 PM JST, Yury Norov wrote:
>
> ...
>
>> > Allocating a pool with 0-bit capacity is wrong. Please don't put it
>> > in the examples. I recall I pointed that this object would panic the
>> > kernel if, for example, you call pool.next_zero_bit(0) immediately
>> > after this. Sorry, but NAK.
>> >
>> > This .with_capacity() should take num_ids: NonZero, after all...
>>
>> This panic is not specific to the size zero, any size triggers the same
>> behavior when accessed out of bounds.
>
> In C, malloc(0) is implementation defined behavior, i.e. it can return
> a pointer valid for free(), or NULL (which is also valid for free).
>
> This is a very old legacy coming from K&R implementation, then rejected
> in C89, and later this all became an impl-def, mostly for compatibility
> reasons. See 7.20.3 in
>
> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n937.pdf
>
> Rust adopted C bitmaps, thus creating 0-bit bitmap may go through, and
> hit that questionable behavior. You add this example without any
> discussion about all that possible complications, and with no
> protection for users.
>
> Interestingly, you're doing it for the reason that has been considered
> a bad practice for over 30 years ago - malloc(0) with the immediate
> realloc(). See the above link for details.
>
> To me it looks like pulling legacy with a potential of undefined behavior
> into Rust.
A bad historical design in C standard shouldn't be affecting a modern API
design.
Special casing 0 as a size is bad, because all code would then need to care if
something is 0 or not. Imagine that I have a code that want unconditionally put
a generic piece of data to heap via `KBox`, I should be able to write
`KBox::new(data)` directly without having to do `if size_of::<T>() == 0`.
Special casing 0 break the nice code composition properties.
Rust standard library does not repeat the mistake in its allocation
implementations (and same for our in-kernel allocator abstraction). All
zero-sized allocation are well-defined to return a pointer that is valid for,
well, 0 bytes.
In fact, in kernel we also did the sensible thing -- make 0 byte allocation
defined. `kmalloc(0)` is not a bug and it'll return you `ZERO_SIZE_PTR` which
you can then give to `kfree`. For `krealloc`, both reallocating from 0 to
non-zero or the other way is defined.
Best,
Gary