malloc(0)

Per Bothner bothner at sevenlayer.cs.wisc.edu
Sun Jul 15 08:28:01 AEST 1990


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).) This behavior is
actually *required* for C++, according to Ellis&Stroustrup:
The Annotated C++ Reference Manual, and it would be nice if
it were at least *permitted* in C.

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

    4.10.3 Memory management functions

    The order and contiguity of storage allocated by successive calls to
    the calloc, malloc, and realloc functions is unspecified.  The pointer
    returned if the allocation succeeds is suitably aligned so that it may
    be assigned to a pointer to any type of object and then used to access
    such an object or an array of such objects in the space allocated (until
    the space is explicitly freed or reallocated).  Each such allocation
    shall yield a pointer to an object disjoint from any other object.  The
    pointer returned points to the start (lowest byte address) of the allocated
    space.  If the space cannot be allocated, a null pointer is returned.
    If the size of the space requested is zero, the behavior is implementation-
    defined; the value returned shall be either a null pointer or a unique
    pointer.  The value of a pointer that refers to freed space is
    indeterminate.

One suggested interpretation is that "a unique pointer" means a
globally static/fixed address. Another is a "pointer to an object
disjoint from any other object." This is seems more reasonable to
me. 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.

	--Per Bothner
bothner at cs.wisc.edu Computer Sciences Dept, U. of Wisconsin-Madison



More information about the Comp.std.c mailing list