malloc(0)

Doug Gwyn gwyn at smoke.BRL.MIL
Tue Jul 24 04:17:51 AEST 1990


In article <10830 at spool.cs.wisc.edu> bothner at sevenlayer.cs.wisc.edu (Per Bothner) writes:
>I'm trying to clarify the allowed implementation of malloc(0).
>I'm hoping the standard permits malloc(0) to
>actually allocate memory (for each call). (In other words,
>a implementation is allowed to in essence convert malloc(0)
>to malloc(small_positive_integer).)

A conforming implementation may do that, or it may always return a null
pointer.  If the pointer is non-null, it should point to a storage region
having a distinct address from all other object and 0-malloc()ed addresses.

>The question hinges of the meaning of the phrase "unique pointer" below:

No, the important issue is that there are no 0-sized objects in C, so
the program making a malloc(0) call is not strictly conforming, and thus
a conforming implementation is free to interpret the malloc(0) request
as it sees fit; however, other constraints should be obeyed.  The clear
intent of the pointer uniqueness requirement is to ensure that equality
of valid pointers implies that the same object is pointed to by both
pointers.  If it were not for this requirement, all malloc(0) requests
could be satisfied by returning a constant pointer to some valid library
object.  As it is, however, a distinct pointer should be handed out for
each active malloc(0).  Since each allocated block normally has an
associated bookkeeping header in front of it, this is easy to accomplish
with linked-list allocation schemes.  With a "buddy system" allocator
special care must be taken to change the size from 0 to some positive
value.  (I don't recommend "buddy system" allocators anyway.)

>However, the definition of realloc() (4.10.3.4) seems
>to conflict with the latter interpretation:
>    If SIZE is zero and PTR is not a null pointer, the object it points
>    to is freed.

It's not a conflict, just a reason to be careful if you want to exploit
an implementation's extended malloc(0) support.



More information about the Comp.std.c mailing list