I want write a repeating pattern of bytes into a block of memory. My idea is to write the first example of the pattern, and then copy it into the rest of the buffer. For example, if I start with this:
ptr: 123400000000
Afterward, I want it to look like this:
ptr: 123412341234
I thought I could use memcpy to write to intersecting regions, like this:
memcpy(ptr + 4, ptr, 8);
The standard does not specify what order the copy will happen in, so if some implementation makes it copy in reverse order, it can give different results:
ptr: 123412340000
or even combined results.
Is there any workaround that lets me still use memcpy, or do I have to implement my own for loop? Note that I cannot use memmove because it does exactly what I’m trying to avoid; it make the ptr be 123412340000, while I want 123412341234.
I program for Mac/iPhone(clang compiler) but a general answer will be good too.
There is no standard function to repeat a pattern of bytes upon a memory range. You can use the
memset_pattern*function family to get fixed-size patterns; if you need the size to vary, you’ll have to roll your own.Be aware that
memset_pattern4,memset_pattern8andmemset_pattern16exist only on Mac OS/iOS, so don’t use them for cross-platform development.Otherwise, rolling a (cross-platform) function that does a byte-per-byte copy is pretty easy.