0
section .data

; This array is sorted
sorted_arr:     dq      1, 2, 3, 4, 5, 6, 7, 8, 9, 10
arr_len:        equ     $ - sorted_arr

; These are not
unsorted_arr1:  dq      1, 2, 3, 4, 5, 7, 6, 8, 9, 10
unsorted_arr2:  dq      2, 1, 3, 4, 5, 6, 7, 8, 9, 10
unsorted_arr3:  dq      1, 2, 3, 4, 5, 6, 7, 8, 10, 9

fmt:            db      "%d", 10, 0

section .text
global main
extern printf

main:
    push rbp
    mov rbp, rsp

    mov rdi, sorted_arr
    mov rsi, arr_len
    call is_sorted

    mov rsi, rax
    mov rdi, fmt
    call printf

    mov rdi, unsorted_arr1
    mov rsi, arr_len
    call is_sorted

    mov rsi, rax
    mov rdi, fmt
    call printf

    mov rdi, unsorted_arr2
    mov rsi, arr_len
    call is_sorted

    mov rsi, rax
    mov rdi, fmt
    call printf

    mov rdi, unsorted_arr2
    mov rsi, arr_len
    call is_sorted

    mov rsi, rax
    mov rdi, fmt
    call printf

    pop rbp
    mov rax, 0
    ret


is_sorted: 
    push rbp
    mov rbp, rsp
   
    mov rcx, 9
     
.loops:
    mov rbx, rdi
    
    mov rax, qword[rdi+8]
    cmp rax, [rbx]

    jl .end
    add rdi, 8
     
    dec rcx
    cmp rcx, 0
    je .fin
    loop .loops

.end
    mov rax, 0
    pop rbp
    ret

.fin
   mov rax,1
   pop rbp
   ret

    
    
    ; Return 1 for sorted, 0 for not sorted

the output im getting is

1
1
0
0

what am i doing wrong here?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Dman
  • 1
  • 3
  • Did you run in the debugger? – Something Something Feb 24 '23 at 19:14
  • i did but im really new at asm and i dont understand it that well to be honest – Dman Feb 24 '23 at 19:15
  • note that you check `unsorted_arr2` twice, never `unsorted_arr3`. So you don't know if it's correct for that test-case either. – Peter Cordes Feb 24 '23 at 19:16
  • ahh thank you didnt notice that – Dman Feb 24 '23 at 19:17
  • 2
    Your loop decrements RCX twice per iteration. [How exactly does the x86 LOOP instruction work?](https://stackoverflow.com/q/46881279) shows how to write the bottom of a normal loop, with `dec ecx` / `jnz .loops` (`dec` sets FLAGS other than CF according to the result, like from `cmp ecx, 1` before the decrement). Watching register values as you single-step in a debugger would catch this. See GDB asm tips at the bottom of https://stackoverflow.com/tags/x86/info – Peter Cordes Feb 24 '23 at 19:18
  • my question isnt a duplicate, why was it closed, i hate this website – Dman Feb 24 '23 at 19:26
  • It's not an exact duplicate, but it's a trivial bug of using `loop` when you probably wanted `jmp`, so one way to look at it is that you didn't understand exactly what the `loop` instruction does. If you search, you can probably find other Q&As that are more exact duplicates, where the problem was using `dec rcx` inside a `loop` loop. If you find one, I can add that as another duplicate for future readers with the same problem who somehow manage for find this question. – Peter Cordes Feb 26 '23 at 02:27

0 Answers0