The C standard function memcpy
is sometimes implemented in a similar manner like this. This function has no requirement that the addresses passed by the application are aligned.
A naive version could just run a for loop using char
byte type and copy everything byte by byte. Then we don't have to worry about alignment, but such code will be slow since it isn't taking advantage of the CPU data width.
More efficient code will do the copying on the largest data size that the CPU can handle in a single instruction, such as for example 32 or 64 bits. This is supposedly what this code is supposed to do. If we do that, we still have to take care of potential misalignment in the start and trailing bytes in the end of the segment to be copied. That part has to be copied byte by byte, similar to the code at the end of your function.
This is the first place where we notice that the code you posted is severely broken - it doesn't handle initial misalignment.
Worse yet, it assumes that int cpu_size = sizeof(char *);
gives the CPU data width size which is just plain wrong - the size of a pointer corresponds to the address bus width which is not the same thing as the maximum data register width on a whole lot of existing systems.
Another problem/bug is that temp += cpu_size;
isn't valid C code but a non-standard gcc extension. We can't do pointer arithmetic on void pointers.
Cosmetic bugs are the casts between void*
and void*
. Obviously we don't need to cast between the same types. Every object pointer in C can in fact get implicitly converted to a void*
without casts, given that qualifiers (const
etc) match.
And finally, we can't run code such as this on a standard C compiler, because de-referencing some unknown data with a value access of long
or int
is very likely undefined behavior and a strict aliasing violation. What is the strict aliasing rule? The actual memcpy function as part of the standard lib isn't written in standard C and can't get compiled as it. (It is quite likely written in assembler and often inlined in the calling code.)
So what you should do with this code here is to delete it and forget that you ever saw it, because there's nothing to learn from it. The person who wrote it didn't know what they were doing. With the "Yoda conditions" obfuscation it looks like code from the 1980s - if so, then I'd recommend to avoid studying really old code like that.