【问题标题】:Order of declared variables with printf (assembly)使用 printf(程序集)声明变量的顺序
【发布时间】:2015-03-06 01:04:12
【问题描述】:

这是我的工作代码:

.section .data
prompt:
    .asciz "Please input value:\n"
input:
    .asciz "%d"
output:
    .asciz "output: %d\n"
integer:
    .int
.section .text
.globl  main
main:
    nop

    pushl $prompt
    call printf
    addl $8, %esp

    pushl $integer
    pushl $input
    call scanf
    addl $8, %esp

    movl integer, %ecx
    pushl %ecx
    pushl $output
    call printf
    add $8, %esp

    pushl $0
    call exit

如果我改变顺序,为什么会这样:

input:
    .asciz "%d"
output:
    .asciz "output: %d\n"
integer:
    .int

到(其中integer 高于其input

integer:
    .int
input:
    .asciz "%d"
output:
    .asciz "output: %d\n"

...然后它不再打印出您扫描的整数?是不是因为我们先引用了$integer,然后把它压入栈中?

【问题讨论】:

    标签: assembly x86 gnu-assembler att


    【解决方案1】:

    您实际上需要为.int 指定一个值,否则它不会做任何事情。因此,在第二种情况下,您的整数(即 4 个字节)也与 inputoutput 的开头重叠。假设您输入的数字在最高有效字节中为零(即任何小于2^24 的非负数),您将有效地将输出字符串截断为零长度。

    要修复它,您只需执行.int 0 或在.bss 部分中声明您的整数,例如使用.lcomm integer, 4

    【讨论】:

    • 如果您能稍微澄清一下,我想知道为什么 4 字节在第二种情况下重叠,但如果我要声明为零,请不要这样做。是不是零先分配了4个字节,然后在4个字节之后开始input的下一个32位内存地址,否则input的内存地址直接在integer的32位地址之后?
    • 是的,如果您不分配值,那么integer 将与input 具有相同的地址。
    猜你喜欢
    • 2016-12-15
    • 2016-05-12
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多