inixsoftware
inixsoftware

Reputation: 678

NASM Print Integer With Printf

I have been trying the following code to print the number 0 to the console screen:

SECTION .data

DAT0:
    db 0
DAT1:
    db "%d"

SECTION .text
global _main
extern _printf

_main:
push DAT0
push DAT1
call _printf
add esp, 8

ret 0

however, instead of printing 0, it prints 4210688. What exactly is going wrong?

This was assembled & linked using NASM and MinGW

Upvotes: 0

Views: 2664

Answers (1)

szx
szx

Reputation: 6926

You're pushing the address, not the number itself. Since your number is only 1 byte, you need to load it with sign-extension and then push that 32-bit integer.

movzx eax, byte [DAT0]
push eax
push DAT1
call _printf
add  esp, 8

Or you could change your format string to use "%hhd" to print an 8-bit integer. Then it would be ok to load 3 bytes of garbage following your number, because x86 is little-endian.

push  dword [DAT0]         ; push a 4-byte memory source operand
push  fmt                  ; push the address of the format string
call  _printf
add   esp,8

...
fmt: db  "%hhd", 0xa, 0   ; print signed char as a number, not a character

Note that printf expects a 0-terminated C string, so you must have a ,0 at the end of it. It might happen to work if you get lucky and there was 0 padding after your DAT1.

Upvotes: 2

Related Questions