Date: Thu, 02 Dec 2004 00:56:17 -0500 From: "Brandon S. Allbery KF8NH" <allbery@ece.cmu.edu> To: JINMEI Tatuya / =?UTF-8?Q?=E7=A5=9E=E6=98=8E=E9=81=94?= =?UTF-8?Q?=E5=93=89?= <jinmei@isl.rdc.toshiba.co.jp> Cc: current@FreeBSD.org Subject: Re: malloc(0) returns an invalid address Message-ID: <1101966976.4877.16.camel@rushlight.kf8nh.com> In-Reply-To: <y7v1xe9p87u.wl@ocean.jinmei.org> References: <y7vfz2qpltw.wl@ocean.jinmei.org> <MDEHLPKNGKAHNMBLJOLKMEAKADAB.davids@webmaster.com> <y7v1xe9p87u.wl@ocean.jinmei.org>
next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, 2004-12-02 at 00:41, JINMEI Tatuya / 神明達哉 wrote: > > pointer, once you cast it to a 'char *', you cannot dereference it because > > it does not point to a character. This same problem would occur with > > 'malloc(1)' and 'int *'. > > BTW: the "same problem" (of segfault) does actually NOT occur with > malloc(1) and int * on FreeBSD 5.3 (i386). I suspect malloc(3) takes > a special action with the size of zero. I believe he misspoke; the result is undefined in that case, since it's not generally possible to enforce a writable size of 1 in hardware(*) and malloc() is required to return memory aligned for any fundamental C type regardless of the amount of memory allocated (i.e. malloc(1) isn't permitted to return an odd address on hardware where types larger than (char) must be aligned). With a size of 0 it's easy to cheat: return a "magic" minimal-sized pointer into an unmapped page (or a read-only page, getting you a trap if something tries to assign to it; but I think the low pages in the address space are not mapped for standard demand-paged executables on FreeBSD), and when it's realloc()ed to a non-zero size recognize the "magic" value and return a real chunk of allocated memory. (*) it can be done on some processors/MMUs, on others it can be done for a limited number of addresses (Intel debug registers?), on still others (e.g. Intel 486) the best granularity you can get is 16-byte and it's going to be expensive... -- brandon s. allbery [linux,solaris,freebsd,perl] allbery@kf8nh.com system administrator [WAY too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon univ. KF8NH
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?1101966976.4877.16.camel>