How does the internal implementation of memcpy work?

后端 未结 3 1385
执念已碎
执念已碎 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:56

    A trivial implementation of memcpy is:

     while (n--) *s2++ = *s1++;
    

    But glibc usually uses some clever implementations in assembly code. memcpy calls are usually inlined.

    On x86, the code checks if the size parameter is a literal multiple of 2 or a multiple of 4 (using gcc builtins functions) and uses a loop with movl instruction (copy 4 bytes) otherwise it calls the general case.

    The general case uses the fast block copy assembly using rep and movsl instructions.

提交回复
热议问题