tarabyte
tarabyte

Reputation: 19172

How to copy memory starting at address finer than the addressable granularity of your system?

I'm thinking about memcpy, where the src pointer that is passed might be an odd memory address. Is this possible? And, if so, can it be implemented?

If for my system, memory is addressable in 32bit (4Byte) blocks:

0x00001000
0x00001020
0x00001040
0x00001060

How can I copy five bytes from midway in an array whose contents begin at 0x00001000, e.g. the contents of address 0x00001050 through 0x00001078 inclusive?

Does the memcpy implementation always have to copy byte-by-byte?

Upvotes: 2

Views: 279

Answers (1)

Tim Cooper
Tim Cooper

Reputation: 10468

This works fine in all versions of C, all platforms - a C compiler wouldn't be compliant with the C standard if the parameters to memcpy() needed to be word-aligned.

If you look under the hood you'll see that memcpy() is always faster if src and dst are word aligned, and special tricks are needed to cope with the more general case of e.g. odd pointers, because then it needs to go down to the level of bytes. But that is not your worry - you just use the function and trust that it works.

Upvotes: 3

Related Questions