c - NASM 程序集 while 循环计数器

标签 c loops gcc assembly nasm

我正在汇编中编写一个 while 循环,以便使用 nasm 和 gcc 在 Linux 终端中进行编译。该程序比较 x 和 y 直到 y >= x 并在最后报告循环数。这是代码:

segment .data

out1    db "It took ", 10, 0
out2    db "iterations to complete loop. That seems like a lot.", 10, 0
x       db 10
y       db 2
count   db 0

segment .bss

segment .text

global main
extern printf

main:
    mov    eax, x
    mov    ebx, y
    mov    ecx, count
    jmp    lp         ;jump to loop lp

lp:
    cmp    ebx, eax   ;compare x and y
    jge    end        ;jump to end if y >= x
    inc    eax        ;add 1 to x
    inc    ebx        ;add 2 to y
    inc    ebx
    inc    ecx        ;add 1 to count
    jp     lp         ;repeat loop

end:

    push    out1      ;print message part 1
    call    printf

    push    count     ;print count
    call    printf

    push    out2      ;print message part 2
    call    printf

    ;mov    edx, out1               ;
    ;call   print_string            ;
                                    ;
    ;mov    edx, ecx                ;these were other attempts to print
    ;call   print_int               ;using an included file
                                    ;
    ;mov    edx, out2               ;
    ;call   print_string            ;

这是在终端中编译和运行的:

nasm -f elf test.asm
gcc -o test test.o
./test

终端输出如下:

It took
iterations to complete loop. That seems like a lot.
Segmentation fault (core dumped)

我看不出逻辑有什么问题。我认为这是语法问题,但我们才刚刚开始学习汇编,我尝试了各种不同的语法,例如变量周围的括号和在段末尾使用 ret,但似乎没有任何效果。我还搜索了段错误,但没有发现任何真正有用的东西。任何帮助将不胜感激,因为我是一个绝对的初学者。

最佳答案

它崩溃的原因可能是您的main 函数没有ret 指令。还要确保将 eax 设置为 0 以表示成功:

xor     eax, eax ; or `mov eax, 0` if you're more comfortable with that
ret

此外,全局变量指定指针,而不是值。 mov eax, xeax 设置为x 的地址。如果您希望发生任何事情(或不使用全局变量),则需要写回它。

最后,您使用一个非字符串参数调用 printf:

push    count     ;print count
call    printf

第一个参数需要是格式字符串,如"%i"。这里,count 是一个指向空字节的指针,因此您什么也得不到。别想了,你应该试试这个:

out3    db "%i ", 0

; snip

push    ecx
push    out3
call    printf

关于c - NASM 程序集 while 循环计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933263/

相关文章:

linux - 针对特定的 glibc ABI

c++ - 全局函数和不明确的参数 NULL 与 char* 在 vs 2013 和 GCC 之间

创建简单的显示

c - C代码优化-防止多文件打开

python - 将嵌套的 for 循环转换为等效的 map

python - 如何通过 while 循环以 python 方式避免此代码重复?

c - 获取 avro 字符串时出错

c - 将随机索引选取到排序数组中

python - 对dict中所有 "key":"value"pair进行运算,并将结果存入一个新的dict对象中

C++ 编译器输出