malloc(0)

Daniel Elbaum dan at oresoft.com
Fri Jul 27 09:22:16 AEST 1990


In <13384 at smoke.BRL.MIL> gwyn at smoke.BRL.MIL (Doug Gwyn) writes:

>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).

>A conforming implementation 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.

How can one zero-sized object be the "same" as another?   Since C
does not have zero-sized objects, a program must not do anything
with that which is pointed to by the return value of malloc(0).  If
an implementation chooses to return a valid pointer to an object of
no particular size, it's still illegal to use that object.  The
pointer is "unique" insofar as it can only be obtained by a call
to malloc or calloc with a zero argument.  Is this meaning of
"unique" consistent with the wording and intent of 4.10.3?

>>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.

"Freeing" an object appears to mean, according to 4.10.3.2, making
that object available to future calls to malloc() and calloc().  If
the object is already available in a way that does not conflict with
4.10.3, then the call to free() is permitted to have nil effect.
-- 
Being conservative in most respects and reluctant to transform country and
constitution, the coup d'etat typically neither attracts nor needs the fanatic.

({uunet,tektronix,reed,sun!nosun,m2xenix}!oresoft!(dan)@oresoft.com)



More information about the Comp.std.c mailing list