【问题标题】:Assembly EAX register behaves oddly汇编 EAX 寄存器行为异常
【发布时间】:2013-09-23 14:45:43
【问题描述】:

我对汇编还很陌生,并试图从标准输入中读取一个值(从 C 中调用 scanf 函数)并将其打印回标准输出(使用 printf)。


.text
readstr:    .asciz "%d"     #string used for calling scanf
printstr:   .asciz "%d\n"   #string used for calling printf

.global main

main:   movl    %esp, %ebp  #initialize base pointer
    call    inout

    pushl   %eax
    pushl   $printstr
    call    printf

    pushl   $0      #push exit code to stack
    call    exit    #exit with the exit code

inout:  pushl   %ebp
    movl    %esp, %ebp

    subl    $4, %esp
    leal    -4(%ebp), %eax
    pushl   %eax
    pushl   $readstr
    call    scanf

    movl    %ebp, %esp
    popl    %ebp
    ret

预期的输出将与输入的数字相同,但输出始终是

1

注意:在 64 位 suse linux 企业桌面上编译,使用 gcc -m32 -o inout inout.s

这里出了什么问题?

【问题讨论】:

  • 您正在编写非常不正确的汇编代码,没有正确获取函数参数和返回值,并使堆栈不平衡。使用 C 编译器并查看其汇编输出以确保正确。
  • 我强烈建议您学习如何使用调试器。然后,您可以单步执行代码,检查寄存器和内存位置以查看它们是否包含您希望它们在每个点包含的内容。如果您的期望和您看到的不匹配,要么您的代码被破坏,要么您的理解被破坏,您可以调试其中任何一个。

标签: assembly x86


【解决方案1】:

调用scanf()后,%eax包含函数的返回值,即the number of input items assigned。在您的情况下,这始终是 1,因为始终只有一个输入项。

在从inout() 返回之前,您需要将-4(%ebp) 的值放入%eax

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 2012-01-02
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多