Converting to a pointer type for which the pointer value is
misaligned yields undefined behavior in itself.
On a system where that in fact generates an error, malloc(1) could not
returned an insufficiently aligned address. But on a system where
that is not the case, malloc(1) *is* sufficiently aligned for all the
things you can legally do with it. That is, these systems behave *as
if* malloc(1) was sufficiently aligned for a double.[/QUOTE]
I think I agree.
Suppose sizeof(double)==8, and double requires 8-byte alignment. But
suppose that converting a misaligned char* pointer to double* (which
invokes undefined behavior) simply copies the bit pattern, and never
causes anything "bad" to happen. In other words, attempting to access
a misaligned double object can crash your program, but constructing a
misaligned pointer to double cannot. (These are assumptions about a
particular hypothetical implementation.)
Then the standard's definition of malloc() explicitly requires
double *ptr = malloc(1);
(assuming it succeeds) to set ptr to a value that's properly aligned
(i.e., 8-byte aligned) for type double -- but there's no way for a
portable program to detect a violation of this requirement. So I
think the "as if" rule applies.
If a tree is misaligned in a forest and nobody can access it, does it
invoke undefined behavior?
Note that if the result of malloc(1) is misaligned, then
realloc(ptr, sizeof(double))
will not be able to expand the allocated space in place; it must
allocate a *new* properly aligned 8-byte block. This doesn't argue
that malloc(1) can't yield a misaligned pointer, merely that the
implementation must take some extra care if it does so.