Re: How does C cope if architecture doesn't address bytes?

From: Richard Bos (
Date: 11/18/04

Date: Thu, 18 Nov 2004 08:09:12 GMT

"James Harris" <> wrote:

> "Christian Bau" <> wrote in message
> <snip>
> > Now lets say you want to allocate an array for 100 doubles; one double
> > is a native word of eight bytes. You will have sizeof (double) = 8, 100
> > * sizeof (double) = 800, and malloc (800) returns a pointer to an array
> > of 100 native words.
> This is making more sense to me now. I'm a bit confused by the use of 800
> in the malloc call above. Would malloc (100 * sizeof(double)) be more
> portable? To be portable should all calls to malloc except chars specify
> sizeof()?

Very much so, yes. In fact, there's an even better way than using sizeof
(type). You nearly always assign malloc() to a pointer object. You can
use sizeof *pointer instead of sizeof (type). For example, instead of

  struct foo *head;
    ... lots of code ...
  head=malloc(number * sizeof (struct foo));

you can write

  struct foo *head;
    ... lots of code ...
  head=malloc(number * sizeof *head);

Now the malloc() call remains correct even if maintenance makes it
necessary for you to make head a struct bar *, instead - and you don't
even have to remember to change all malloc() calls! You can't even
accidentally overlook one.
This style is not, btw, more portable than that with sizeof (type), but
it is more solid and maintainable.

> Incidentally, K&Rv2 in 7.8.5 Storage Management says than malloc returns a
> pointer which has the proper alignment for the object in question. I can't
> see that it can know for sure what the space is to be used

Well, the implementation is allowed to use whatever magic is available
to it. For example, TTBOMK it's legal for it to scan the statement in
which the malloc() call occurs, figure out the type of the pointer which
it is assigned to, and instead of writing CALL (malloc), @ACC, @PTR to
the object code, write CALL (mallocalign), @ACC, @SIZ, @PTR. However...

> for so assume that malloc always returns a block of memory with the
> coarsest alignment required by the implementation.

...most implementations seem to do this, probably because trying to
optimise alignment would be a lot of trouble for very little gain.