gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:26:17 24 4
gpt4 key购买 nike

我正在汇编中编写一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com