Search code examples
assemblyx86gnu-assembleratt

Order of declared variables with printf (assembly)


Here is my working code:

.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

Why is it that if I change the order of:

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

to (where integer is above its input)

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

...then it no longer prints out your scanned integer? Is it because we reference $integer first, when we push it onto the stack?


Solution

  • You need to actually specify a value for .int, otherwise it won't do anything. So in the second case, your integer (which is 4 bytes) overlaps the input and the start of output too. Assuming you input a number that has a zero in the most significant byte (that is any non-negative number less than 2^24) you will effectively truncate the output string to zero length.

    To fix it you can just do .int 0 or declare your integer in the .bss section for example using .lcomm integer, 4.