Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!ucbvax!sdcsvax!sdchem!tps From: tps@sdchem.UUCP (Tom Stockfisch) Newsgroups: net.unix,net.unix-wizards,net.arch,net.lang.c Subject: Re: get size of malloc'd object Message-ID: <240@sdchema.sdchem.UUCP> Date: Wed, 18-Jun-86 19:08:33 EDT Article-I.D.: sdchema.240 Posted: Wed Jun 18 19:08:33 1986 Date-Received: Fri, 20-Jun-86 03:10:42 EDT References: <165@daisy.UUCP> <334@valid.UUCP> <2206@peora.UUCP> Reply-To: tps@sdchema.UUCP (Tom Stockfisch) Organization: Chemistry Dept, UC San Diego Lines: 42 Xref: watmath net.unix:8240 net.unix-wizards:18468 net.arch:3501 net.lang.c:9461 In article <2206@peora.UUCP> jer@peora.UUCP (J. Eric Roskos) writes: > > It is really hard to come up which general purpose algorithmic > solutions to problems without having even a glimmer of what > environment you are talking about ... > >Sure it is. Just write your own routine to call malloc; allocate a >sizeof(int) worth of extra space, then store the size of the thing you >malloc'ed in the int at the front of the allocated block, advance the >pointer past the place where your stored the size, and return that as >the pointer to the block you allocated. The size of the object is then >found in the word preceeding the location pointed to by the object pointer. >... >This approach is portable, simple, and easy to understand. >Also it doesn't require any assumptions about what kind of objects are >being allocated. >-- >E. Roskos This is NOT portable. Suppose your machine requires "doubles" to be aligned on addresses divisible by 8 and sizeof(int) == 4. You do double *dp = (double *)my_malloc( (unsigned)100 * sizeof(double) ); If my_malloc() calls malloc() and then increments the pointer returned by malloc by 4, you will get a segmentation fault as soon as your allocated space is accessed. A *portable* way to do this (which wastes a little memory, but doesn't require that you know the worst-case alignment size) is to hand both the unit size and number of units to my_malloc() and allocate one extra *unit* to store the size of the space in. Of course, if the unit size < sizeof(int) you have to do a little extra diddling. Usually when I need to know the end of the allocated space I need to access it too often to be done by a subroutine call so I set up a structure to replace the pointer: struct foo { arraytype *beg; /* begining of array */ arraytype *end; /* end of array */ } bar; -- Tom Stockfisch, UCSD Chemistry