4 ms·
Can someone tell me a usecase where you want multiple allocations of size 0, each one with a unique address, and each one unique from any other allocation (henc
by Lvl999Noob 1y ago
Can someone tell me a usecase where you want multiple allocations of size 0, each one with a unique address, and each one unique from any other allocation (hence necessarily removing that pointer from being allocated to anything else) but can't use malloc(1) instead?
I think it would be much better if malloc(0) just returned 1 or -1 or something constant. If the programmer needs the allocation to have a unique address, they can call malloc(1) instead.
- hansvm 1y agoIt's occasionally useful to want multiple allocations of size 0, each one with a valid address -- generic containers parsing something as a some sort of sequence object and you want all code interacting with it to do something valid. I'd be hard-pressed to see where you'd need those to be unique though. Basically any integer should be fine.
- xenadu02 1y agoBecause zero-size types exist which you might want to take the address of. Possibly as a result of macro substitution or templating mechanism that only appears in certain build configurations. It means you don't need a bunch of special-case handling if one out of 27 types ends up with zero size in some situation. It just all works the same way. Especially the unique address part because that would be an annoying source of difficult to track bugs.
- Lvl999Noob 1y agoYes. I believe zero sized types should be possible and they should all have the same address. Trying to deref the pointer is UB right away because you do not have the byte under that pointer. As it is, the malloc implementation now needs special casing for 0 sized allocations and different implementations special case it differently. C is supposed to be low level so surface this confusion up. Let the programmer decide if they want a unique address and reserve a byte or a non unique one with no overhead.
- zzo38computer 1y agoZero sized types (and zero-length arrays, empty structures, etc) can be useful, and should not need to all have the same address (although in some cases they will have the same address, and in other cases it won't matter what the address is as long as it is nonzero), although you probably should not need to use dynamic allocation directly with such a type. GNU C has a Elvis operator so that you can write "malloc(x?:1)" if you really need to do that. If only a unique reference is needed (if it won't be used where other kind of pointers would also be used), and keeping track of allocation is wanted, one thing that may be possible is to just use a number, and then use a bit array to keep track of which numbers are in use.
- tliltocatl 1y agomalloc(1) have high overhead because of minimum allocation size and heap tags. malloc(0) can return a known-invalid address (i. e. from higher half) with a counter.