Search code examples
assemblygnu-assembleratt

Pushing and printing float value in assembly


I writing a compiler as my university project. I am on the stage of code generating. And I'm wondering why this isn't working (prints always 0):

.extern printf
.section .data
hello:
    .string "Hello %f!\n"
.section .text
.globl main
main:
    pushl %ebp
    movl %esp, %ebp

    pushl $3214514586 // or pushl $0xbf99999a
    pushl $hello
    call printf

    leave
    ret

but this works correctly:

.extern printf
.section .data
hello:
    .string "Hello %f!\n"
.section .text
.globl main
main:
    pushl %ebp
    movl %esp, %ebp

    pushl $3214514586 // or pushl $0xbf99999a

    flds (%esp)
    fstpl (%esp)

    pushl $hello
    call printf
    leave
    ret

Solution

  • In C float argments to a varargs function (such as printf) are promoted to double. Your second code converts the 4-byte float to an 8-byte double so that it passes the correct value to printf, however it overwrites the saved value of ebp so may crash.