standards/62858: malloc(0) not C99 compliant

Stefan Farfeleder stefan at fafoe.narf.at
Sat Feb 14 15:50:24 PST 2004


>Number:         62858
>Category:       standards
>Synopsis:       malloc(0) not C99 compliant
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    freebsd-standards
>State:          open
>Quarter:        
>Keywords:       
>Date-Required:
>Class:          sw-bug
>Submitter-Id:   current-users
>Arrival-Date:   Sat Feb 14 15:50:21 PST 2004
>Closed-Date:
>Last-Modified:
>Originator:     Stefan Farfeleder
>Release:        FreeBSD 5.2-CURRENT i386
>Organization:
>Environment:
System: FreeBSD wombat.fafoe.narf.at 5.2-CURRENT FreeBSD 5.2-CURRENT #13: Thu Feb 5 23:10:05 CET 2004 stefan at wombat.fafoe.narf.at:/usr/home/stefan/freebsd/obj/usr/home/stefan/freebsd/src/sys/WOMBAT i386

>Description:
A recent discussion in the newsgroup comp.std.c (Subject: Re: Memory question)
revealed that ISO/IEC 9899:1999 does not allow malloc(0) to return the same
non-null pointer each time it is called.

# 7.20.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 deallocated). The lifetime of an allocated object extends
# from the allocation until the deallocation. 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: either a null pointer is returned, or the behavior is as if the size were some
                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# nonzero value, except that the returned pointer shall not be used to access an object.
  ^^^^^^^^^^^^^

The C89 wording about an "unique pointer" was dropped.

>How-To-Repeat:
This strictly conforming C99 program fails due to malloc()'s non-compliance:

#include <assert.h>
#include <stdlib.h>

int
main(void)
{
	void *p, *q;

	p = malloc(0);
	q = malloc(0);
	assert(p != q || p == NULL);
	return (0);
}

>Fix:
Either enabling malloc()'s V flag by default or adding
'if (size == 0) size = 1;' should make malloc() compliant.
>Release-Note:
>Audit-Trail:
>Unformatted:


More information about the freebsd-standards mailing list