Ark said:
Eric said:
[...]
Why does the Standard tread on this
shaky ground? Because it needs to be able to require that
malloc() return addresses that satisfy whatever alignment
requirements the machine might impose, for example.
Ain't it good enough to say that malloc returns (on success) an
address good for storing any data type? (With no alignment in scope
The Standard might have chosen to say that the allocated
area shall be suitable for storing any data type whose sizeof
is not too large, but what it actually says is a bit stronger.
Since all alignment requirements are satisfied, the address
returned by malloc() can be stored in any kind of pointer
variable, even on machines where pointers to different types
have different "precision." For example,
double *p = malloc(1); /* assume alignof(double) > 1 */
must not "damage" the returned value by doing something like
discarding low-order bits that a `double*' doesn't need. A
subsequent free(p) must work properly, meaning that it must
be possible to reconstruct any discarded bits.
The "you can store it if it's not too big" criterion would
allow malloc(1) to return an unaligned address, and on a machine
where converting that address to a `double*' would change it,
that would not be a Good Thing.
Perhaps the Standard could have avoided talking about
alignment if it instead imposed an "assignable to any pointer"
requirement. But this isn't the only place the notion crops
up; it also appears as the reason structs might be padded, as
the reason you might not be able to store a double at "just
any" address, and so on. I imagine that the writers would
rather not have mentioned it, but the elephant would still
have been in the drawing room.
Indeed so. If the Standard said, plainly, that an address good for
storing a short is good for storing a char, etc. -- there would be a
tad less confusion and much less fights over definitions.
It *does* say that any object can be accessed as an array
of bytes, hence that any address can store a char. But it doesn't
say that any address suitable for a long is also suitable for a
double, or for a long double, or for a struct foobar -- that would
put the Standard in the position of dictating machine design. The
Standard does a lot of fancy footwork to stay out of the way of
machine designers as much as it can.