Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!apple!snorkelwacker!bloom-beacon!eru!hagbard!sunic!mcsun!ukc!stc!rmj From: rmj@tcom.stc.co.uk (Rhodri James) Newsgroups: comp.lang.c Subject: Re: ** help... Message-ID: <1912@islay.tcom.stc.co.uk> Date: 29 Aug 90 19:07:24 GMT References: <2409@dsacg2.dsac.dla.mil> <1884@jura.tcom.stc.co.uk> <11245@crdgw1.crd.ge.com> Reply-To: rmj@htc1.UUCP (Rhodri James) Organization: STC Telecomms, Harlow Technical Centre, Harlow Lines: 47 In article <11245@crdgw1.crd.ge.com> volpe@underdog.crd.ge.com (Christopher R Volpe) writes: >In article <1884@jura.tcom.stc.co.uk>, rmj@tcom.stc.co.uk (Rhodri James) >writes: >|>3) this isn't vastly relevant to PC applications, but doing a >|>multiplication as your argument to malloc is just asking for alignment >|>trouble. Either calloc(xL, sizeof(int *)), or (more grungily) >|>malloc(sizeof(int *[xL])) (will this work if xL is a variable?) Several people have pointed out to me that it won't work if xL is a variable. I wasn't sure, but I really should have known. Thankyou, one and all. And now to business. >First, malloc doesn't know or care (and couldn't find out if it wanted >to) whether the argument being passed in is a constant expression >(like sizeof(anything)) or an expression computed at runtime via >a multiplication. My copy of K&R II says (section 7.8.5) that the >pointer returned by malloc or calloc has proper alignment for the >object in question. My manpage (SunOS 4.0.?) says that calloc USES >malloc to allocate the storage, and then initializes it to zeros. Yes, K&R 2 says the *pointer* has proper alignment for the object in question, by taking the most restrictive possibility, and I wouldn't be surprised if calloc were implemented by using malloc. However, note the emphasis and read on... >[...] the value produced [by sizeof(int *[xL]) if it were legal] would be the >same as (xL * sizeof(int *)), so malloc wouldn't know the difference. This is not guarenteed true for all types by anything I can find in K&R 2. The crux of the potential health hazard comes with the definition of sizeof, which K&R2 says (section 6.3) gives a size_t result equal to the size of the specified object or type in bytes. Nothing here guarentees that the *end* of the object will be such that another object straight after it in memory (which is what the multiplication implies) will be correctly aligned. Many structs would give appropriately odd lengths; I'm sure you don't need examples. I admit I jumped too fast on int *, which is OK (probably, on most modern machines), and I don't have a copy of the standard. Can anyone quote chapter and verse invalidating this argument (please)? -- * Windsinger * "Nothing is forgotten..." * rmj@islay.tcom.stc.co.uk * Mike Whitaker * or (occasionally) * "...except sometimes the words" * rmj10@phx.cam.ac.uk * Phil Allcock