首页 > 解决方案 > 我在 x86 中收到我不理解的分段错误

问题描述

我有这个汇编程序,它接受三个参数(指向 int 数组的指针、大小和目标)并且需要编写线性搜索,但是在我尝试过的每个实例中,我一直收到分段错误。


    section .text

; function should return the index at which the target was found

; Parameter 1 is a pointer to the int array
; Parameter 2 is the size of the array
; Parameter 3 is the target element to find in the array

linearSearch:
    push rbx        ; int i[] (the array)
    push r12        ; int j (array.size())
    push r13        ; int k (the element to find)
    xor r10, r10        ; pointer to an index of the array
    xor r14, r14        ; count to keep track of size searched
    xor rax, rax        ; initialize rax as 0 to avoid random nonsense
    jmp loop        ; head into loop to find element

    mov r14, 0      ; initialize count as 0
    mov r10, rbx        ; r10 = first element of i[] 

loop:
    cmp r14, r12        ; count >= j ? jmp end : continue
    jae endNotFound     ; jump to int not found end
    cmp r10, r13        ; i[r10] == k ? je end : continue
    je end          ; jump to int found end
    inc r14         ; increase counter for amount searched by one
    mov r10, [rbx+4*r14]    ; set index pointer equal to r14+1 (4 being the size of int in 64-bit)
    jmp loop        ; rinse and repeat

endNotFound:
    mov rax, -1     ; by convention, return -1 if the int cannot be found
    pop r13
    pop r12
    pop rbx
    ret
end:
    mov rax, r10        ; move index pointer to rax to be returned  
    pop r13
    pop r12
    pop rbx
    ret

最初,我认为问题是我遇到了某种随机变量问题,所以我用 xor 将非参数变量初始化为 0,但仍然收到相同的错误。我错过了什么?或者更好的是,从概念上讲,我忘记了什么会导致这些分段错误,因为这不是我第一次遇到这个问题,而且很可能是同一件事。

标签: assemblyx86segmentation-faultx86-64

解决方案


推荐阅读