4 ms·
To me it seems more reasonable to draw the insanity line at returning NULL for a successful zero byte allocation. (While it's true that dereferencing a pointer
by bjornsing 11y ago
To me it seems more reasonable to draw the insanity line at returning NULL for a successful zero byte allocation.
(While it's true that dereferencing a pointer to a zero byte allocation should probably trigger undefined behavior that doesn't mean that it shouldn't be possible to do the != NULL test to see if the allocation was successful.)
- akeruu 11y agoTo me, the insanity is trying to allocate zero byte
- bjornsing 11y agoAgree, but that's not the allocator's sanity though.
- zAy0LfpBZLC8mAC 11y agoThat's because you think of it as a special case, which it isn't. If you want to store a string that's n bytes long, you need to allocate n bytes, so a natural thing to write is, for example dst.len=strlen(src);dst.buf=malloc(dst.len); --it's insanity if you need to add a special case for strings of a specific length.
- tbirdz 11y agoA standard C string will never be 0 bytes. There is the zero terminator at the end of the string, so all strings will be at least 1 byte large.
- carussell 11y agoThe example is clearly forgoing the use of standard C strings for a char array tagged with the length.
- acqq 11y agoYou don't have to call malloc directly in the second assignment. If you depend on special handling of null without the "if" on invocation you can have your own function for that.
- gpderetta 11y agoAs it guaranteed to work by the appropriate standards, there are programs that use zero bytes allocations to get a process wide unique cookie. edit: turns out that no, neither C11 nor C++11 guarantee that, it was probably historical behaviour.