|
|
Subscribe / Log in / New account

Realloc freed the memory long before the C99 standard.

Realloc freed the memory long before the C99 standard.

Posted Oct 24, 2024 16:05 UTC (Thu) by Wol (subscriber, #4433)
Parent article: realloc() and the oversize importance of zero-size objects

Option 2 (free the object and return NULL) predates the C99 standard by quite a lot. The glibc implementation might not ...

I remember reading my Microsoft C v5.1 (from 1991-ish?) where it says realloc with a size of 0 frees the memory and returns NULL.

Imho this is a very good way of assuring safety - if you do not use free, but instead always do "ptr = realloc( ptr, 0)", you will never (absent multiple copies of a pointer) have dangling pointers lying around.

Cheers,
Wol


to post comments

Realloc freed the memory long before the C99 standard.

Posted Oct 24, 2024 18:05 UTC (Thu) by fman (subscriber, #121579) [Link] (3 responses)

>> 2. Behave like free(), release the object, and return NULL.

And further: How (in this context) is NULL *not* a pointer that can be passed to free().
So in this regard 2) is just a specialization of 1)

Presumably, both 1) and 2) would free() the incoming argument pointer.

Realloc freed the memory long before the C99 standard.

Posted Oct 24, 2024 18:11 UTC (Thu) by randomguy3 (subscriber, #71063) [Link] (2 responses)

i believe the key word is "unique" - NULL is definitely not a unique pointer value!

Realloc freed the memory long before the C99 standard.

Posted Oct 24, 2024 18:12 UTC (Thu) by randomguy3 (subscriber, #71063) [Link]

(looking back, "unique" is not mentioned in 1 in that list, but is mentioned earlier in a quote from glibc's docs)

Realloc freed the memory long before the C99 standard.

Posted Nov 1, 2024 0:50 UTC (Fri) by kelnos (subscriber, #174370) [Link]

A long long time ago, the first time I ever read that, I thought it meant that it would return the single same pointer value every time you called malloc() with a size of 0. But that value was also guaranteed to never be returned for a non zero sized allocation. To me the second bit was the "unique" part. And so returning NULL could be a conformant thing to do. As could (as someone else suggested) returning (void *)-1 every time.

I know no one actually interprets or implements it that way, but to me, that's still a valid reading of the spec.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds