What does malloc(0) return?

Blair P. Houghton bhoughto at hopi.intel.com
Sat Jun 1 10:02:25 AEST 1991


In article <16317 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
>In article <11614 at ncar.ucar.edu> steve at unidata.ucar.edu (Steve Emmerson) writes:
>>The subject-line says it all and my K&R2 is silent on the matter.
>
>malloc(0) should return either NULL or a pointer to some storage location.
>Technically the behavior is undefined, since there are no objects of the
>specified size (0) according to the standard.

The memory-allocation functions have an "out" for that semantic:

	"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."
		 (ANSI X3.159-1989, sec. 4.10.3, p. 155, ll. 18-20)

What it says is that it is guaranteed not to point to any
previously accessible object.  Presumably the rest of your
code is careful enough to keep track of the amount of space
it has requested and react correctly if the space is
zero-sized.

But, the pointer, if it is returned, points to an address
which is correctly aligned for _any_ object.  Whether this
has any use I do not know.  However, it does mean that
malloc() may not again return that pointer (not without
free()ing it first), which means it can't use that
alignment, which means the next time it's called it may
return a pointer to the next aligned space in
its managed list.  I.e., `malloc(0)' must "eat" space if it
does not return NULL, though that space is not necessarily
allocated (although this goes out the window if your computer
is capable of implementing pointers that refer to aligned
space that does not exist; e.g., in the case where alignment
is irrelevant and pointers are doubly-indirect...)

Moral:  if you anticipate asking for nonpositive numbers of
chars from malloc(), check the size before calling malloc,
because malloc()'s return-value does not give any hint how
much space you asked for, even if you asked for no space.

				--Blair
				  "Cranial capacity jokes to /dev/malloc(0)"



More information about the Comp.std.c mailing list