|Synopsis:||Pointers shall not be converted to other pointer types.|
Data structures have an alignment. Some structures must start on a 4 byte boundary, while for other structures the boundary is 2 or 1. When a misaligned structure is accessed this can cause an exception, but this differs per processor. In general casting a pointer to a pointer type with stricter alignment requirements is dangerous.
The most common reason to cast between pointers is to convert between a generic pointer (pointing to a memory region) and a specific pointer (pointing to a piece of data stored in this memory region). Therefore conversion between a "void" pointer and a pointer of any other type is allowed and does not require a cast.
To avoid having to cast through a "void" pointer before or after pointer arithmetic it is also allowed to cast between a "char" pointer and any other pointer.
Consider the following where a receiving pointer represents a type which has potentially stricter memory alignment criteria than that of the type being cast:
short *s; /* 2 byte alignment */ int *i; /* 4 byte alignment */ ... i = (int *)s; /* WRONG: potential misalignment */
void *p_sharedmem; CCBB_struct *p_mystruct; p_mystruct = p_sharedmem; /* RIGHT: exception for generic pointers */ p_mystruct->intmember = 1; p_mystruct = (CCBB_struct *)((char *)p_sharedmem + sizeof(CCBB_struct)) /* RIGHT */
If short and int are aligned as stated in the first example above then "s" may have an address that does not represent a legal int address. It would well be possible that an address exception would be generated on access of "i".