Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!hsdndev!cmcl2!adm!smoke!gwyn From: gwyn@smoke.brl.mil (Doug Gwyn) Newsgroups: comp.std.c Subject: Re: What does malloc(0) return? Message-ID: <16319@smoke.brl.mil> Date: 2 Jun 91 00:03:34 GMT References: <11614@ncar.ucar.edu> <16317@smoke.brl.mil> <4538@inews.intel.com> Organization: U.S. Army Ballistic Research Laboratory, APG, MD. Lines: 39 In article <4538@inews.intel.com> bhoughto@hopi.intel.com (Blair P. Houghton) writes: >In article <16317@smoke.brl.mil> gwyn@smoke.brl.mil (Doug Gwyn) writes: >>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. > "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) Oops, thanks for pointing that out. (I remembered the committee debate on the issue, but not the outcome.) Thus the "should" in my response becomes a "must" and "undefined" should have been "implementation-defined". I think, but am not sure, that malloc()ed storage is intended to be such that the address (one past the end) of the requested amount of storage be meaningful (but its "contents" not necessarily accessible), just as for explicitly declared arrays. >I.e., `malloc(0)' must "eat" space if it does not return NULL, ... The rest of that discussion seemed confusing. I think it is easier to simply say that the implementation has the choice (which must be documented) of EITHER simply returning NULL for a 0-sized request, OR acting in effect as though the request had been for just 1 byte. In some situations the ability to not actually make the additional storage accessible might be of some use to the implementor; however, since a strictly conforming program cannot count on 0-sized malloc()s succeeding even when there is plenty of unallocated storage available, it is hardly worth making such an optimization for this special case (which hardly any program will ever tickle). Generally I would think that reasonable implementations of malloc() would naturally support successful 0-sized allocations with no special coding for the 0-sized case. Certainly this would be true for "block header" style schemes; for "buddy system" schemes (which I don't recommend), there would have to be a simple fudge (such as "if(bytes_wanted==0)++bytes_wanted;" to obtain the required "unique pointer" property.