Kevin Goodsell <us*********************@neverbox.com> writes:
[...]
There's no obvious reason why the compiler would complain about
this. Conversion from void * to any other object pointer type is
allowed. However, it could fail at runtime if the alignment is
incorrect. You cannot, in general, take any random memory location and
interpret it as an arbitrary type. Some types may need to be aligned
on particular addresses - for example, a two-byte short might need to
appear at an even address.
One obvious workaround for this is to use memcpy().
For example:
void *ptr = some_value;
short s;
/* s = *((short*)ptr); */
memcpy(&s, ptr, sizeof(short));
In the assignment statement that I commented out, ptr is converted
from void* to short*, and the result is dereferenced, yielding a short
value which is assigned to s. However, this will invoke undefined
behavior if ptr isn't properly aligned. (For example, if ptr points
to an odd address, you're likely to get a bus error, but this is
implementation-specific; all you really need to know is Don't Do That.)
The memcpy() call does essentially the same thing, but it operates
byte-by-byte, so it won't have problems with misaligned pointers.
(The implementation of memcpy() might be optimized to copy data a word
at a time if it's safe to do so.)
This assumes that the data ptr points to has the correct byte
ordering. If a short is 2 bytes long, the high-order and low-order
bytes can appear in either order. This can be an issue if you're
copying data from one platform to another. If you read and write the
data on a single system, you probably don't have to worry about this.
A digression: When I wrote "all you really need to know is Don't Do
That", I meant that that's all you need to know to write correct code.
If programming were just about writing correct code, though, we'd all
have a lot more free time. C's "undefined behavior" covers any
possible or impossible behavior, but knowing something about the
implementation-specific details can be extremely useful in tracking
down bugs. (For the most part, those details are best discussed in
implementation-specific newsgroups, though.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)