Search code examples
cassemblygnu-assemblerattmemset

memset movq giving segfault


I am getting a segfault at the movq (%rsi, %rcx) line.

I know you can't do mem->mem mov, so I did it through a temporary register. (%rsi), %rcx, then in the loop %rcx, (%rdi). Here is my code:

experimentMemset:   #memset(void *ptr, int value, size_t num)

                                 #%rdi     #%rsi        #%rdx


movq %rdi, %rax             #sets rax to the first pointer, to return later


.loop:
    cmp $0, (%rdx)          #see if num has reached 0
    je .end
    cmpb $0, (%rdi)         #see if string has ended also
    je .end

    movq %rsi, %rdi       #copies value into rdi

    inc %rdi        #increments pointer to traverse string
    dec %rdx        #decrements the count, aka num
    jmp .loop



.end:
     ret

Solution

  • As you discovered, RDX holds a size (an integer count), not a pointer. It's passed by value, not by reference.

    cmp $0, (%rdx)

    compares not the register, but the location pointed by it. It seems that %rdx is used as a counter, so you should compare the register itself.

    test %rdx,%rdx ; je count_was_zero

    There are other bugs, like checking the contents of the write-only destination for zeros, and not storing %sil into (%rdi). But this was the cause of the segfault in the current version of the question.