linux - NASM Linux 32 位 : scanf, printf 调用

标签 linux assembly printf nasm scanf

我编写了简单的汇编代码,它使用 printfscanf 分别在命令行写入和读取数字。对于这个特定的代码,我m 得到与给定输入不同的输出。打印的第一个值似乎是 [var1]+[var2]*2^8 。但是,通过将变量 var1var2 的大小增加到 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

最佳答案

您告诉 scanfprintf 您正在扫描/打印整数,这些整数通常是 32 位(或 4 字节)值。所以他们的行为就好像他们在您提供的地址使用那么多数据一样。

关于linux - NASM Linux 32 位 : scanf, printf 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29780878/

相关文章:

Java:Printf(%.2f,arg) 显示 f$ff 而不是 f.ff。什么可能导致这种情况?

c - 如何在 c 中打印动态数量的占位符?

linux - 在 SUSE 上使用 reviewboard 进行 subvertpy 安装

python - Windows 到 Linux 脚本问题 : "IndexError: list index out of range"

c++ - 相对于 C 的内联汇编性能优势

c - 如何将包含 32 位 asm 的 C 程序编译成 .o 文件?

使用 printf 参数的变量调用 printf、snprintf、f_printf 等

linux - 如何将多个二进制文件通过管道传输到从标准输入读取的应用程序

c - 尝试加载 BPF 程序时参数无效 (EINVAL)

assembly - 如何使用 DASM 直接设置字节?