How does the internal implementation of memcpy work?

后端 未结 3 1380
执念已碎
执念已碎 2021-01-01 13:10

How does the standard C function \'memcpy\' work? It has to copy a (large) chunk of RAM to another area in the RAM. Since I know you cannot move straight from RAM to RAM in

3条回答
  •  情话喂你
    2021-01-01 13:47

    The implementation of memcpy is highly specific to the system in which it is implemented. Implementations are often hardware-assisted.

    Memory-to-memory mov instructions are not that uncommon - they have been around since at least PDP-11 times, when you could write something like this:

        MOV FROM, R2
        MOV TO,   R3
        MOV R2,   R4
        ADD LEN,  R4
    CP: MOV (R2+), (R3+) ; "(Rx+)" means "*Rx++" in C
        CMP R2, R4
        BNE CP
    

    The commented line is roughly equivalent to C's

    *to++ = *from++;
    

    Contemporary CPUs have instructions that implement memcpy directly: you load special registers with the source and destination addresses, invoke a memory copy command, and let CPU do the rest.

提交回复
热议问题