Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NASM x86 print integer using extern printf

Tags:

c

x86

nasm

I try to print an integer using printf in x86 assembly. For the format string printf(fmtstring, vals) i have stored the %d as fmtd. Then i put 1 into ax, 2 into bx, add them and want to print the result using call printf. Here is the code.

global _main

extern _printf

section .data
    fmtd db "%d"

section .text

_main:
    push ebp
    mov ebp, esp

_begin:
    mov ax, 1
    mov bx, 2
    add ax, bx
    push ax
    push fmtd
    call _printf
    add esp, 8

_end:
    mov esp, ebp
    pop ebp
    ret

but i get

-10485757

instead of expected

3

can you help me whats wrong with it?

When i just write

push 3
push fmtd
call _printf

it works as usual and prints 3.

Thank you


1 Answers

You need to use the full 32 bit registers:

You want this:

mov eax, 1
mov ebx, 2
add eax, ebx
push eax
push fmtd
call _printf

Explanation of output -10485757 you get:

-10485757 in hexadecimal is FF600003. The 0003 comes from the push ax which pushes the 16 low bits of eax. The FF60 is whatever leftover was on the stack.

Reads this SO article for detailed explanation about the relationship between ax and eax.

like image 175
Jabberwocky Avatar answered Sep 10 '25 02:09

Jabberwocky