O
Old Wolf
To sum up:
1. Not all pointers are created equal.
2. Void and char pointers are compatible due to historical reasons.
3. Void pointers can point to anything.
They can't point to functions. Although it is a very common
extension (eg. POSIX includes it) to allow void pointers to point
to functions.
4. Typed pointers can point to void objects only if the object is
properly aligned to not need the extra information contained in the
void pointer. That is, it only needs the 'base address'.
There are no "void objects", and a void pointer need not have
"extra information" (it could just be extra non-useful junk),
and 'base address' is not necessarily a part of it. Try this:
Typed pointers can point to objects iff the object is properly
aligned for that pointer type.
I've been writing code for years on various 8, 16 & 32 bit
platforms but never noticed this subtlety. Anything else
I'm missing?
Have you ever programmed on a SPARC (Sun) CPU ? They have
alignment and the program blows up if you violate it. Try this:
int main(void)
{
char *pc = malloc(10);
int *pi = (int *)(pc + 1);
*pi = 0;
}
It's possible for compilers to 'work around' this by noticing if
you do an unaligned access, and converting your code into a bunch
of instructions to work with chars. But gcc, for one, doesn't do
this by default.
Many embedded platforms also have "forced" alignment like this.
Other platforms such as IA32 allow unaligned accesses, but they
just run slower (the CPU will break it up into multiple single-
char accesses, behind the scenes).