我在彙編中編寫了一個while循環以便在帶有nasm和gcc的Linux終端中編譯。該程序比較x和y,直到y> = x並報告最後的循環數。下面的代碼:NASM程序集while循環計數器
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
,但似乎沒有任何效果。我也搜索了分段錯誤,但我還沒有發現任何真正有用的東西。任何幫助將不勝感激,因爲我是一個絕對的初學者。
非常棒的幫助,謝謝,輸出現在'花了134520932次迭代......很多。你能解釋一下在這種情況下寫回eax嗎?使用'mov eax,[x]'沒有像我想的那樣幫忙。另外,我在main的末尾添加了'mov eax,0'和'ret',但仍然出現分段錯誤,有什麼想法?另外,你會介意解釋'mov eax,0'和'ret'的用途嗎? – vroom
就這樣,沒有。考慮使用'gdb'來找出崩潰的位置。 (另外,我剛剛注意到你正在用'jp'跳回去,你確定你不是指'jmp'嗎?) – zneak
對於'mov eax,0'和ret',這是因爲否則,沒有指示告訴你的程序結束。執行將繼續執行零字節(意思就像'add al,0'或者其他),直到它到達分配內存的末尾,然後崩潰。當一個函數返回時,它的結果應該在'eax'中,所以我們基本上在這裏說「return 0」,如果你有任何C的概念。 – zneak