3 ms·
erm... allocating zero was never a good idea. it had varying behaviours on varying platforms for as long as i could remember and was one of those special cases
by jheriko 11y ago
erm... allocating zero was never a good idea. it had varying behaviours on varying platforms for as long as i could remember and was one of those special cases to avoid.
the allocators didn't necessary even meet the alignment specification either... even if the documents said they did. i remember reading that malloc on windows would return things on 8-byte boundaries only to find pointers ending in 4 (rather than 0 or 8) coming out of it...
and as many have pointed out returning null may or may not happen in a number of situations. i've seen it happen enough times when i ask for too much memory to believe that it is a useful fail case to check for...
- kazinator 11y agorealloc(ptr, 0) special case which (on some C libraries only) means the same thing as free(ptr) and not to realloc the object to zero size. That's what the author's resize function expected, which is why his patch is to use free.
- fanf2 11y agoC libraries do not conform to the standard if they do not free in this case.
- masklinn 11y agoThat requirement was present in C89 and removed in C99, which also added that a 0-sized allocation doesn't have to return a null pointer (whether done by malloc, calloc or realloc)
- kazinator 11y agoDang, is that right? See, I checked C99 when I posted the comment. I don't know where my old copy of C90 is, but I was mildly surprised. I had that WTF feeling "I could have sworn it was supposed to work that way! In any case, if I'm compiling with -ansi or -std=c90 on a GCC-based platform that is hosted, the library had better behave in the C90 conforming manner. Only if if -std=c99 is used should it take the liberty with realloc(ptr, 0) being like malloc(0).
- jheriko 11y agoC libraries do not conform to the standard.
- cperciva 11y agoerm... allocating zero was never a good idea. it had varying behaviours on varying platforms for as long as i could remember and was one of those special cases to avoid. No, allocating zero bytes is a perfectly reasonable thing to do, as long as you remember that NULL is not necessarily an allocation failure. if (((buf = malloc(buflen)) == NULL) && (buflen > 0)) goto OUTOFMEMORY; is perfectly good code.
- jheriko 11y agothats not even close to reasoning imo, its just an assertion. ... but i agree that the code is safer if you check for bad cases. i can't see why allocating zero ever is more sensible than not doing it at all (and therefore avoiding even having to know about this problem, much less deal with it).