D
David Mathog
Sorry if this is in the FAQ, been through it a couple of times and
could not find a clear answer.
The question concerns this code snippet:
long *lvar;
char *cvar;
lvar = malloc(132);
cvar=malloc(132);
Presumably the C compiler will always align the memory allocated on
the 3rd line so that the
132/sizeof(long) long's that could be stored there are properly
aligned for the target machine. The
question is, given the existence of the longer data type, must the
memory returned in the last line _also_ be properly aligned for longs?
For instance it was claimed here:
http://bytes.com/topic/c/answers/220448-how-get-aliagned-memory-using-malloc
that
The C standard specifies that malloc() and family will allocate
memory
so that the address can be used for any data type. This means that
malloc() and family must be familiar with and able to accomodate the
restrictions the underlying platform place on the arrangement of
data
items in memory.
malloc is a low level routine and its only parameter is the size of
the memory to allocate. It would seem that the only way to reconcile
the quote above with the single parameter nature of malloc would be to
have malloc always return an address which is the least common
multiple of all defined data types for the target. Or are compilers
allowed to replace malloc with malloc_4bytes, malloc_2bytes
etc., to achieve an alignment appropriate for only the target pointer,
but possibly not for larger types?
Thanks,
David Mathog
could not find a clear answer.
The question concerns this code snippet:
long *lvar;
char *cvar;
lvar = malloc(132);
cvar=malloc(132);
Presumably the C compiler will always align the memory allocated on
the 3rd line so that the
132/sizeof(long) long's that could be stored there are properly
aligned for the target machine. The
question is, given the existence of the longer data type, must the
memory returned in the last line _also_ be properly aligned for longs?
For instance it was claimed here:
http://bytes.com/topic/c/answers/220448-how-get-aliagned-memory-using-malloc
that
The C standard specifies that malloc() and family will allocate
memory
so that the address can be used for any data type. This means that
malloc() and family must be familiar with and able to accomodate the
restrictions the underlying platform place on the arrangement of
data
items in memory.
malloc is a low level routine and its only parameter is the size of
the memory to allocate. It would seem that the only way to reconcile
the quote above with the single parameter nature of malloc would be to
have malloc always return an address which is the least common
multiple of all defined data types for the target. Or are compilers
allowed to replace malloc with malloc_4bytes, malloc_2bytes
etc., to achieve an alignment appropriate for only the target pointer,
but possibly not for larger types?
Thanks,
David Mathog