scanf将变量设置为0 NASM

时间:2017-02-27 10:05:10

标签: assembly nasm

我试图写一个"猜数字" linux上的nasm游戏, 我有一个问题,我不明白...... 当scanf被执行时,我的变量mysteriousNumber被设置为0,我不知道为什么...... 有人可以解释一下我做错了什么? (对不起我的英语技能)

;  GuessTheNumber
;  mainasm : user have to guess the randomly generated number
;
extern printf
extern rand
extern srand
extern time
extern puts
extern scanf

    SECTION .data
string_welcome: db "Welcome to the GuestTheNumber game",0xa,0x0
string_ask: db "Enter a number between 1 and 100",0xa,0x0
string_higher: db "The number is higher ",0xa,0x0
string_lower: db "The number is lower",0xa,0x0
string_win: db "YOU WIN",0xa,0x0
string_format: db "%d",0x0


enteredNumber: dw 999
mysteriousNumber: dw  0

    SECTION .text       ; code section
        global main     ; make label available to linker

main:               ; standard  gcc  entry point
    push ebp
    mov ebp,esp

    push string_welcome
    call printf
    add esp,0x4

    push 1                  ; numberMin
    push 100                ; numberMax
    call generateNumber     ; generateNumber between nubmerMin to numberMax
    add esp, 0x8
    mov [mysteriousNumber],eax
    mov edx , 0
loop:
    push string_ask
    call printf      ; printf("Enter a number ")
    add esp,0x4

    push enteredNumber
    push string_format
    call scanf
    add esp,0x8

    mov ebx, DWORD [enteredNumber]
    mov eax, DWORD [mysteriousNumber]
    cmp eax,ebx
    jb below
    jg higher
    jmp win
below:
    push string_lower
    call printf
    add esp,0x4
    jmp loop
higher:
    push string_higher
    call printf
    add esp,0x4
    jmp loop

win:
    push string_win
    call printf
end:
    mov ebx,0       ; exit code, 0=normal
    mov eax,1       ; exit command to kernel
    int 0x80        ; interrupt 80 hex, call kernel
  leave
  ret

generateNumber:
    push ebp        ; prolog
    mov ebp,esp

    push 0x0
    call time       ; call time(NULL)

    push eax        ; set arg1 = time(NULL)
    call srand      ; call srand(time(NULL))

    mov ebx,DWORD [ebp+0x8] ; ebx = numbermax
    mov ecx,DWORD [ebp+0xc] ; ecx = numbermin
    sub ebx,ecx     ; ebx = numbermax - numbermin
    inc ebx         ; ebx = numbermax -numbermin + 1
    call rand

    xor edx,edx
    div ebx         ; edx = rand%ebx
    inc edx         ; edx =

    mov eax,edx    ; eax = MysteryNumber

    leave
    ret

1 个答案:

答案 0 :(得分:2)

您正在使用"%d"对于scanf,它改变了一个int(在这种情况下为32位值)

你的变量只有16位("输入编号:dw ..."),你输入的高16位会覆盖第二个变量

使用" dd"而是变量