C structs & A question about octet

Joseph S. D. Yao jsdy at hadron.UUCP
Mon Nov 24 16:55:44 AEST 1986


In article <589 at rdin.UUCP> perl at 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 at seismo.{CSS.GOV,ARPA,UUCP}
			jsdy at hadron.COM (not yet domainised)



More information about the Comp.lang.c mailing list