Re: Use of memcpy() to transfer from memory to a variable
- From: Hallvard B Furuseth <h.b.furuseth@xxxxxxxxxxx>
- Date: Fri, 25 May 2007 15:52:58 +0200
Richard Heathfield writes:
Martin said:
For reasons I won't go into, I need to transfer from 1 to 3 bytes to a
variable that I know is 4 bytes long. Bytes not written to in the
4-byte target variable must be zero. Is the following use of memcpy()
a well-defined way of so doing?
No, but it's not exactly undefined either.
It is if it produces a trap representation in the 'long' variable. Due
to either padding bits in the long type, or on a sign/magnitude host
where it can produce negative zero, which can be a trap representation.
Not exactly common, but it's possible. And if you use unsigned long
instead, it's possible to trap it at compile time by checking that
ULONG_MAX uses all the bits in a long.
if ( rem )
{
value = 0;
memcpy( &value, pAddress, rem );
}
/* for demo - shows values in pAddress have been transferred */
printf("value = 0x%0lX\n", value);
Note that you need to look out for C's aliasing rules in code like that.
I _think_ it's safe when pAddress holds a malloced char array, but
otherwise the compiler would be allowed to "know" that pAddress does not
hold a long and 'value' thus is not set to a long after 'value = 0;'.
Then it could optimize away the memcpy, since it can tell the
destination value is not used (validly).
Compilers get smarter all the time, I remember a recent comment from the
gcc guys about some other hack: "We are working on a feature which will
break your hack."
Sigh. I guess we'll have to throw away hash functions which read
aligned data in larger chunks than byte by byte soon... Or maybe it
would help to declare the input values volatile.
--
Regards,
Hallvard
.
- Follow-Ups:
- Re: Use of memcpy() to transfer from memory to a variable
- From: Richard Heathfield
- Re: Use of memcpy() to transfer from memory to a variable
- References:
- Use of memcpy() to transfer from memory to a variable
- From: Martin
- Re: Use of memcpy() to transfer from memory to a variable
- From: Richard Heathfield
- Use of memcpy() to transfer from memory to a variable
- Prev by Date: Re: IDE for beginner
- Next by Date: Re: Indent C preprocessor directives
- Previous by thread: Re: Use of memcpy() to transfer from memory to a variable
- Next by thread: Re: Use of memcpy() to transfer from memory to a variable
- Index(es):
Relevant Pages
|
Loading