组装中有输入的分段错误

时间:2018-10-07 16:05:38

标签: assembly x86-64

我正在尝试在汇编中实现递归阶乘函数。当我直接将数字压入堆栈时,它可以工作,但是当我尝试使用输入时,却遇到了分段错误。

源代码:

.section .text
    formatstr: .asciz   "%d \n"
    formatscan: .asciz "%1d"                                

.global main

main:
    //push $4                    <---- this works   

    push %rbp
    movq %rsp, %rbp

    subq $8, %rsp   
    movq $0, %rax
    leaq    -8(%rbp), %rsi                  <--- this doesn't work  
    movq    $formatscan, %rdi                   
    call    scanf                               

    call factorial                                  
    addq $8, %rsp                                   
    movq %rax, %rbx                                 

    movq    $0, %rax                                
    movq    $formatstr, %rdi                        
    movq    %rbx, %rsi                              
    call    printf                                  

factorial:
    pushq %rbp                              
    movq %rsp, %rbp                         
    movq 16(%rbp), %rax                     
    cmpq $1, %rax                           
    je end_factorial                        
    decq %rax                               
    pushq %rax                              
    call factorial                          
    movq 16(%rbp), %rbx                     
    imul %rbx, %rax                         

end_factorial:
    movq %rbp, %rsp
    pop %rbp                
    ret                                     

0 个答案:

没有答案