signuts said:
I am wondering what it means when a pointer is aligned?
Could someone perhaps enlighten me or point me in the right direction?
Since this isn't directly C related off-topicality warning:
<OT>
There are several architectures where e.g. an integer must start at
an even address (or addresses that can be divided by 4). This is
related to the machines commands for e.g. loading an int from memory
into the CPU: when an int gets loaded it's probably done using a
machine instruction that roughly translates to "load word from
memory address 0xc73204". If you try to load a "word" from an odd
address this machine instruction does not work and you get a bus
error.
But in C you can write code that looks like this (error checking
omitted):
int a;
unsigned char *buf = malloc( 128 );
a = * ( int * ) ( buf + 1 );
malloc() will always return memory that's properly aligned, i.e.
the address you get can be used for all kinds of types without
running into danger of getting a bus error. So buf will be an
even address. But when you now try to assign to 'a' in the way
it's done above, you try to load 'a' from an odd memory address
and then you're in trouble, at least on machines which require
proper alignment (on other machines this might only result in a
slower memory access). So the above (if it's really necessary)
must be written e.g. as
memcpy( &a, buf + 1, sizeof a );
because memcpy() has to be written in a way that won't use a
"load word" (or similar) instruction that could result in a
bus error.
BTW, this is also the reason why structures often need padding.
If you have a structure like
struct {
char c;
int a;
} my_struct;
the compiler will have to insert at least one extra byte between
'c' and 'a' because otherwise 'a' would end up at an odd address
and
my_struct.a = 0;
might lead to a bus error.
</OT>
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| (e-mail address removed)-berlin.de
_ | | | | | |
| |_| | | | | |
http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring