Re: memcpy strange behavior
Re: memcpy strange behavior
- Subject: Re: memcpy strange behavior
- From: "Sherm Pendley" <email@hidden>
- Date: Thu, 20 Mar 2008 09:48:30 -0400
On Thu, Mar 20, 2008 at 9:25 AM, Nick Rogers <email@hidden> wrote:
> Hi
> I'm using memcpy to copy a file's sector to my struct.
> But its skipping one UInt16 in between and copying the next value in
> the struct's corresponding field.
> I've checked the read sector and its correctly read. My struct is
> also in order.
> Listing:
> memcpy(&myStruct, sector, sizeof(myStruct));
>
> What could be wrong here.
> Any ideas?
Structs can have padding added to them in between members. This is most
often the case when a larger member follows a smaller one, to allow the
larger one to be aligned along a 4-byte or other boundary in memory. On some
architectures, memory access is faster when it's aligned this way.
By the way, even if there were no alignment issues, you'd still have endian
issues - the two bytes of a UInt16 are not stored in memory in the same
order on PPC and Intel.
In other words, memcpy() isn't a reliable way to fill a struct with data
read from a file. You need to know whether the file data is big- or
little-endian, process one element at a time, and use Foundation's
endian-handling functions to swap bytes as needed. You don't need to know
the endianness of the machine your code is running on; these functions are
written to do nothing for data that's already in the CPU's native format.
Alignment issues are discussed here:
<
http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/Introduction.html
>
And the Foundation endian functions, here, in the "Byte Ordering" section:
<
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html
>
sherm--
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden