3 ms·
An allocation of size zero cannot be used for anything useful.
by saagarjha 3y ago
An allocation of size zero cannot be used for anything useful.
- lifthrasiir 3y agoThe caller may still want to distingish a successful yet useless allocation from an unsuccessful allocation, which resulted in the current situation.
- saagarjha 3y agoHow would you tell?
- Nevermark 3y agoZero bytes are always allocatable. Unless you need zero byte (and other) pointers to be consistently unique. But that would mean allocating and deallocating some memory for zero byte requests, to provide unique addresses. Or some reserved memory address span, outside of available (real and virtual) RAM, for zero byte pointers.
- lifthrasiir 3y ago> Unless you need zero byte (and other) pointers to be consistently unique. Yes, this was the problem. People had some different ideas for contracts that `malloc` etc. should guarantee---the most lax requirement would be a "usable" pointer on success, which does almost perfectly constrain non-zero cases but leaves lots of freedom for zero cases. At the opposite side there is a "unique non-NULL" pointer requirement, as you've said, which essentially makes `malloc(0)` almost same to `malloc(1)`. Rust also has this issue because its reference, a pointer after compilation, is expected to be non-null even for zero-sized types. Rust's rule is somewhat in between: any pointer should be non-null, but it doesn't have to be unique for zero-sized types. The canonical non-null pointer for such types (as returned by `NonNull::dangling`) is the smallest non-zero pointer that satisfies the alignment.
- dwattttt 3y agoYou could definitely use it for something useful; you can't store anything through it, but if an allocator supports allocations of size 0 with the same semantics of non-zero allocations, you get a "unique" ptr from the allocator dynamically. Anywhere you need a dynamic list identifier this would suit (yes, a counter could do this too, this would be effectively a globally unique token)
- optimiz3 3y agoOne example is a non-null sentinel/oracle allocation. Often you see this in lockless data structures where you don't want to do a null check.
- eru 3y agoIt should still work. Just like adding 0 to a number should still work, or multiplying by 1. The computer should just happily do nothing.