【问题标题】:Wrong result from assembly program汇编程序的错误结果
【发布时间】:2012-10-17 18:51:42
【问题描述】:

有人可以帮我找出以下程序的问题吗?我正在阅读“从头开始编程”并尝试将示例转换为 x86-64 程序集。下面的程序在一组数据中找到最大的数。但是当我组装、链接和运行它时,我得到 0。这显然不是最大的数字。它在 32 位寄存器/指令下运行良好,但不是 64 位。

# PURPOSE: This program finds the largest value in a set of data.
#
#
# VARIABLES: %rax holds the current value. %rdi holds the largest 
#            value. %rbx holds the current index. data_items is the
#            actual set of data. The data is terminated with a 0.
#

.section .data

data_items:
    .long 76, 38, 10, 93, 156, 19, 73, 84, 109, 12, 21, 0

.section .text
.globl _start
_start:
    movq $0, %rbx
    movq data_items(, %rbx, 4), %rax
    movq %rax, %rdi

loop_start:
    cmpq $0, %rax                     # Have we reached the end?
    je   loop_end
    incq %rbx                         # Increment the index.
    movq data_items(, %rbx, 4), %rax  # Load the next value.
    cmpq %rdi, %rax                   # Is new value larger?
    jle  loop_start
    movq %rax, %rdi                   # New val is larger, store
                                      # it.
    jmp  loop_start

loop_end:
    # The largest value is already in %rdi and will be returned as
    # exit status code.
    movq $60, %rax
    syscall

【问题讨论】:

    标签: assembly x86-64 gnu-assembler


    【解决方案1】:

    您正在使用 movq 从包含 32 位值的列表中移动 64 位值。那会给你错误的结果。将列表定义为保存 64 位值:将 .long 替换为 .quad 并将 4 替换为 mov 中的 8。

    【讨论】:

    • 好的,谢谢。我认为这可能是问题所在,但我不知道 64 位值的指令是什么。在这种情况下使用 movq 而不是具有 .long 值的 movl 有什么好处吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多