Memory mapped NSData byte alignment

I have some data (a few tens of megabytes) consisting of mainly 32 bit integers and 64 bit doubles. I'm considering dumping it all into a file, then memory mapping the file using NSData dataWithContentsOfFile:options:error: passing NSDataReadingMappedAlways.


In Objective-C, I assume if I take the pointer returned by the -bytes method, I can cast it to whatever makes sense (uint32_t *, double * or maybe even a pointer to a packed struct) and do arithmetic on it to give random access to my data. The question is - do I have to worry about byte alignment? Is the pointer returned from -bytes aligned to anything? Suppose I had one 4-byte int then an 8-byte double... if the bytes pointer was 8-byte aligned, the double would then be misaligned. Do I need to care about this?

Replies

When memory mapping, you are responsible for ensuring correct alignment of values assuming you are going to just type cast to copy data in and out of the file. If you use memcpy instead, you won't have to worry about alignment issues.

Thanks. So there is no guarantee on the alignment of the pointer to the start of the block as returned by NSData -bytes?


I was hoping to avoid copying the data unnecessarily but I guess I'll do that if I have to. (Compute pointer to double; if pointer & 0x7 == 0 we're good; else allocate buffer and memcpy?) The latest plan is to punt on the ints and only store doubles in the memory mapped file, so if the first byte is guaranteed to be aligned then I wouldn't have to worry about it.