Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!cbosgd!ihnp4!mhuxn!mhuxr!ulysses!allegra!mit-eddie!genrad!decvax!decwrl!amdcad!amd!pesnta!wjvax!brett From: brett@wjvax.UUCP Newsgroups: net.unix,net.unix-wizards,net.arch,net.lang.c Subject: Re: get size of malloc'd object Message-ID: <718@wjvax.wjvax.UUCP> Date: Fri, 20-Jun-86 11:19:25 EDT Article-I.D.: wjvax.718 Posted: Fri Jun 20 11:19:25 1986 Date-Received: Mon, 23-Jun-86 01:14:19 EDT References: <165@daisy.UUCP> <334@valid.UUCP> <2206@peora.UUCP> Reply-To: brett@wjvax.UUCP (Brett Galloway) Organization: Watkins-Johnson Co., San Jose, Calif. Lines: 32 Xref: watmath net.unix:8331 net.unix-wizards:18555 net.arch:3540 net.lang.c:9537 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. > >Also provide a routine to deallocate the block by backing the pointer up >before calling free(). > >This approach is portable, simple, and easy to understand. >Also it doesn't require any assumptions about what kind of objects are >being allocated. In fact, this assumes that the resulting pointer (malloc(len+sizeof(int))+sizeof(int)) is still well-aligned. This is only true if sizeof(int) is the most coarse alignment boundary on the machine. If, for example, structures require more coarse alignment, attempting to cast the above pointer to a structure pointer will fail. ------------- Brett Galloway {pesnta,twg,ios,qubix,turtlevax,tymix,vecpyr,certes,isi}!wjvax!brett