如何扫描多个整数并将它们存储在数组中?

时间:2017-11-30 06:42:38

标签: assembly scanf x86-64

我是程序集中的新手,我们有这个活动,我们必须在给定用户输入的数组中找到最小数字。我们的讲师给出了关于组装中阵列的示例代码,所以我从那里开始修改了几个部分,我似乎专门用于存储数组中的用户输入。代码如下所示:

;   array = create (size);
create:
push    rbp
mov     rbp, rsp
imul    rdi, 4
call    malloc
leave
ret

;   fill (array, size);
fill:
.array  equ     0
.size   equ     8
.i      equ     16
    push    rbp
    mov     rbp, rsp
    sub     rsp, 32
    mov     [rsp+.array], rdi
    mov     [rsp+.size], rsi
    xor     ecx, ecx
.more   mov     [rsp+.i], rcx

当我开始扫描输入

时,我就在这里获得了分段故障转储
    mov rax,0
    mov rdi,scanner
    mov rsi, input
    call scanf 

其余代码:

    mov     rcx, [rsp+.i]
    mov     rdi, [rsp+.array]
    mov     [rdi+rcx*4], eax
    inc     rcx
    cmp     rcx, [rsp+.size]
    jl      .more
    leave
    ret

;   print (array, size);
print:
.array  equ     0
.size   equ     8
.i      equ     16
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        mov     [rsp+.array], rdi
        mov     [rsp+.size], rsi
        xor     ecx, ecx
        mov     [rsp+.i], rcx
        segment .data
.format:
        db      "%10d", 0x0a, 0
        segment .text
.more   lea     rdi, [.format]
        mov     rdx, [rsp+.array]
        mov     rcx, [rsp+.i]
        mov     esi, [rdx+rcx*4]
        mov     [rsp+.i], rcx
        call    printf
        mov     rcx, [rsp+.i]
        inc     rcx
        mov     [rsp+.i], rcx
        cmp     rcx, [rsp+.size]
        jl      .more
        leave
        ret

;   x = min (array, size);
min:
        mov     eax, [rdi]
        mov     rcx, 1
.more   mov     r8d, [rdi+rcx*4]
        cmp     r8d, eax
        cmovl   eax, r8d
        inc     rcx
        cmp     rcx, rsi
        jl      .more
        ret

main:
.array  equ     0
.size   equ     8

        push    rbp
        mov     rbp, rsp
        sub     rsp, 16

; set default size
    mov ecx, 5
    mov [rsp+.size], rcx

; check for argv[1] providing a size
    cmp edi, 2
    jl .nosize
    mov rdi, [rsi+8]
    call atoi
    mov [rsp+.size], rax

.nosize:

; create the array
    mov rdi, [rsp+.size]
    call create
    mov [rsp+.array], rax

; fill the array with user input
    mov rdi, rax
    mov rsi, [rsp+.size]
    call fill

; if size <= 20 print the array
    mov rsi, [rsp+.size]
    cmp rsi, 20
    jg .toobig
    mov rdi, [rsp+.array]
    call print

.toobig:
; print the minimum
    segment .data

.format:
    db "min: %ld", 0xa, 0
    segment .text
    mov rdi, [rsp+.array]
    mov rsi, [rsp+.size]
    call min
    lea rdi, [.format]
    mov rsi, rax
    call printf

    leave
    ret

0 个答案:

没有答案