Assembly 如何修复32位汇编中的sum_数组函数

Assembly 如何修复32位汇编中的sum_数组函数,assembly,x86,gnu-assembler,Assembly,X86,Gnu Assembler,我试着在堆栈的帮助下对汇编中的数组求和,但结果是不可接受的 当时我试图通过打印ecx寄存器的结果来调试代码。我还尝试使用gdb进行调试,但我不知道如何打印esp或ebp指出的堆栈 .extern printf .extern exit .extern scanf .extern read hex: .asciz "%x" hexn: .asciz "%x\n" intn: .asciz "%d\n" strn: .asciz "%s\n" charn: .a

我试着在堆栈的帮助下对汇编中的数组求和,但结果是不可接受的

当时我试图通过打印ecx寄存器的结果来调试代码。我还尝试使用gdb进行调试,但我不知道如何打印esp或ebp指出的堆栈

.extern printf
.extern exit
.extern scanf
.extern read

hex:    .asciz  "%x"
hexn:   .asciz  "%x\n"
intn:   .asciz  "%d\n"
strn:       .asciz  "%s\n"
charn:  .asciz  "%c"

pr_int:
    pushal
    pushl   %eax
    push    $intn
    call    printf
    addl    $8, %esp
    popal
    ret

pr_str:
    pushal
    pushl   %esi
    call    printf
    addl    $4, %esp
    popal
    ret

pr_hex:
    pushal
    pushl   %eax
    push    $hexn
    call    printf
    addl    $8, %esp
    popal
    ret

pr_char:
    pushal
    pushl   %eax
    push    $charn
    call    printf
    addl    $8, %esp
    popal
    ret

read_hex:
    pushl    %ebp
    movl     %esp, %ebp
    sub     $4, %esp
    # Keep important registers.
    # We can't use pusha here, because the result is inside eax.
    pushl    %ebx
    pushl    %ecx
    pushl    %edx

    leal     -4(,%ebp), %ebp
    pushl    %ebx
    push     $hex
    call    scanf
    addl    $8, %esp
    mov     (,%ebx),    %eax

    # Restore registers:
    popl     %edx
    popl     %ecx
    popl     %ebx
    leave
    ret

我希望sum函数的输出是45,但实际输出是一些随机数。

一个每次运行时都不同的随机数?当然不是,多少。在GDB中,您可以使用
x
检查内存。使用
help x
获取有关格式的信息。是的,每次我运行程序时都会出现一个随机负数。它可能是地址吗?您是否将其链接为每次运行时都会随机化地址的饼图可执行文件(GDB中除外)?无论如何,您可能想要的是
dec%ecx
/
jnz
,而不是
loopne
loopne
在检查ECX是否为非零之前,也会将其递减。不要使用
loop
loopcc
(除了以牺牲速度为代价的代码大小的高级优化)。是的,先生,我可以说它会添加一个地址,这就是十进制中的负数的原因。感谢gdb的帮助。现在我可以打印esp寄存器指出的内容
.include    "include.s"

.section    .text

.align  32
.globl     main

main:
    pushl   $arr
    pushl   $arrlen
    call    sum
    addl    $8, %esp
    call    pr_int
    ret

sum:
    pushl   %ebp
    movl    %esp, %ebp
    xor %edx, %edx
    xor %ecx, %ecx
    movl    20(,%ebp), %ecx

# debugging code
movl    %ecx,   %eax
call    pr_int
xor %eax, %eax
# debugging code ends

    movl    24(,%ebp), %eax
sum_arr:

    addl    (,%eax), %edx
    addl    $4, %eax
    dec %ecx
    loopne  sum_arr
    popl    %ebp
    ret

arr:    .long   1,2,3,4,5,6,7,8,9
arrlen = (. - arr)/4