Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!sundc!hadron!jsdy From: jsdy@hadron.UUCP (Joseph S. D. Yao) Newsgroups: comp.lang.c Subject: Re: C structs & A question about octet Message-ID: <627@hadron.UUCP> Date: Mon, 24-Nov-86 01:55:44 EST Article-I.D.: hadron.627 Posted: Mon Nov 24 01:55:44 1986 Date-Received: Mon, 24-Nov-86 21:55:28 EST References: <2904@rsch.WISC.EDU> <8943@sun.uucp> <589@rdin.UUCP> Reply-To: jsdy@hadron.UUCP (Joseph S. D. Yao) Organization: Hadron, Inc., Fairfax, VA Lines: 25 Summary: Problem with description of malloc() In article <589@rdin.UUCP> perl@rdin.UUCP (Robert Perlberg) writes: >> head = (three_bytes*)calloc(N, sizeof(three_bytes)); >> This wastes N bytes. >It still would even if sizeof(three_bytes)==3. Malloc allocates >storage that is properly aligned for any data type. Therefore, even if >you passed 3 instead of 4, malloc would still skip to the next big >boundary. I suppose that someone could write a calloc that would align >optimally based on the size of the data item being calloc'd, but how >would it know just from the sizeof argument what the proper alignment >for the data type should be? As far as I know, most, if not all, >implementations of calloc just multiply their arguments and invoke >malloc to allocate the storage. You all probably did the multiplication and said, hunh?? after this. The problem is that, even though malloc() returns some- thing longword aligned, if sizeof(...) == 3, then malloc() will get an argument of 3*N, which is 3/4 of 4*N! E.g., for N == 9, malloc() would return 27 (well, 28) bytes instead of 36. As the argument above says, calloc() doesn't know to round the numbers, it just multiplies them. To get each data object on a "proper" longword boundary, the sizeof() returns 4. -- Joe Yao hadron!jsdy@seismo.{CSS.GOV,ARPA,UUCP} jsdy@hadron.COM (not yet domainised)