• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: memcpy strange behavior
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: memcpy strange behavior


  • Subject: Re: memcpy strange behavior
  • From: Jean-Daniel Dupas <email@hidden>
  • Date: Thu, 20 Mar 2008 17:10:50 +0100


Le 20 mars 08 à 16:04, Dave Carrigan a écrit :


On Mar 20, 2008, at 6:48 AM, Sherm Pendley wrote:
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.


The general rule - only to be broken if you absolutely know what you're doing - is that you should never serialize or unserialize structs as a block unless you know for sure that the exact same compiler, right down to the version number and compiler flags, did the serializing as did the unserializing. That generally means that unless the serializing and unserializing code is in the same compilation unit, you cannot read structs as a block and guarantee that it will work as expected. You have to read each field in the struct individually.

--
Dave Carrigan
email@hidden
Seattle, WA, USA

You can also force the struct layout, i.e. __attribute__((packed)). It will not solve the byte order issue, but it may be usefull in some rare occasions.






_______________________________________________

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


References: 
 >memcpy strange behavior (From: Nick Rogers <email@hidden>)
 >Re: memcpy strange behavior (From: "Sherm Pendley" <email@hidden>)
 >Re: memcpy strange behavior (From: Dave Carrigan <email@hidden>)

  • Prev by Date: Re: Where's the buffer overrun?
  • Next by Date: Unloading Launch Daemon app using Cocoa Application
  • Previous by thread: Re: memcpy strange behavior
  • Next by thread: [JOB] Junior Software Engineer
  • Index(es):
    • Date
    • Thread