** help...

Rhodri James rmj at tcom.stc.co.uk
Thu Aug 30 05:07:24 AEST 1990


In article <11245 at crdgw1.crd.ge.com> volpe at underdog.crd.ge.com (Christopher R Volpe) writes:
>In article <1884 at jura.tcom.stc.co.uk>, rmj at 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 at islay.tcom.stc.co.uk   *                    Mike Whitaker
*     or (occasionally)      * "...except sometimes the words"
* rmj10 at phx.cam.ac.uk        *                    Phil Allcock



More information about the Comp.lang.c mailing list