Skip to content
Assembly

memcpy — Copy with rep movsb

Use the rep movsb string instruction for a tight memory copy.

By EZ4Code Team
memorystring-opsrep

Code

; memcpy(dst, src, n)   rdi=dst, rsi=src, rdx=n
section .text
global memcpy

memcpy:
    mov     rax, rdi        ; remember dst for return value
    mov     rcx, rdx        ; count
    rep     movsb           ; copy rcx bytes from [rsi] to [rdi]
    ret

; For aligned, large copies use movsq (8 bytes at a time)
global memcpy_aligned
memcpy_aligned:
    mov     rax, rdi
    mov     rcx, rdx
    shr     rcx, 3          ; rcx = qword count (n / 8)
    rep     movsq
    ; handle the leftover bytes (n % 8)
    mov     rcx, rdx
    and     rcx, 7
    rep     movsb
    ret

Explanation

rep movsb repeats movsb (copy one byte from [rsi] to [rdi], then advance both pointers) rcx times. On modern x86 the CPU microcode recognizes ERMS (Enhanced REP MOVSB) and runs it at near-peak bandwidth, so rep movsb is now the recommended copy primitive. movsq copies 8 bytes per iteration for tighter loops on older CPUs. The dst pointer is returned in rax to match C's memcpy signature.

More Assembly Snippets