我编写了简单的汇编代码,它使用 printf
和 scanf
分别在命令行写入和读取数字。对于这个特定的代码,我m 得到与给定输入不同的输出。打印的第一个值似乎是 [var1]+[var2]*2^8
。但是,通过将变量 var1
和 var2
的大小增加到 4 个字节,代码可以提供正确的输出。怎么办?
;assemble and compile with :
;nasm -f elf testing.asm && gcc -m32 -o testing testing.o
extern printf,scanf
;store eax,ebc,ecx,edx onto the stack
%macro push_reg 0
push edx
push ecx
push ebx
push eax
%endmacro
;restore eax,ebx,ecx,edx
%macro pop_reg 0
pop eax
pop ebx
pop ecx
pop edx
%endmacro
section .text
global main
main:
;reads number var1
push_reg
push var1
push formatin
call scanf ;scanf("%d",var1);
add esp,8 ;restoring stack pointer
pop_reg
;reads number var1
push_reg
push var2
push formatin
call scanf ;scanf("%d",var2);
add esp,8 ;restoring stack pointer
pop_reg
;printing number var1
push_reg
push dword[var1]
push formatout
call printf ;printf("%d",content of var1);
add esp,8 ;restoring stack pointer
pop_reg
;printing number var2
push_reg
push dword[var2]
push formatout
call printf ;printf("%d",content of var2);
add esp,8 ;restoring stack pointer
pop_reg
exit:
mov eax,1
int 0x80
section .bss
var1 resb 1
var2 resb 1
section .data
formatout: db "%d",10,0
formatin: db "%d",0
输入:
1
1
输出:
257
1
最佳答案
您告诉 scanf
和 printf
您正在扫描/打印整数,这些整数通常是 32 位(或 4 字节)值。所以他们的行为就好像他们在您提供的地址使用那么多数据一样。
关于linux - NASM Linux 32 位 : scanf, printf 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29780878/