malloc(5) (wasn't: Re: "do ... while ((NULL + 1) - 1);" ...)

Steve Summit scs at adam.pika.mit.edu
Sun Aug 20 16:04:22 AEST 1989


In article <1527 at cbnewsl.ATT.COM> dfp at cbnewsl.ATT.COM (david.f.prosser) writes:
>Strictly speaking, malloc must return a pointer to an object that
>can be accessed by a type commensurate with its size in bytes.
>Moreover, it may well be possible to argue that unless the requested size
>is a multiple of the size of an int, the returned pointer need not be
>aligned appropriately for an int.  For example, ``malloc(5)''.

I hope not.  This would break the variable-sized structure trick
(discussed here at length not long ago):

	struct string
		{
		int length;
		char text[1];	/* actually text[length] */
		};

where we allocate a "string" with something like:

	(struct string *)malloc(sizeof(struct string)-1+stringlen)

Henry Spencer says that Dennis Ritchie calls this "unwarranted
chumminess with the compiler," but it's widely used.

(Note that (struct string *)malloc(sizeof(struct string)) _would_
work, since sizeof(struct string) will typically be 2*sizeof(int).)

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.lang.c mailing list