1

There is a segmentation fault when I am calling the printf function from function, but it works perfectly fine when being called from the main:

CODE:

extern  printf

SECTION .data
    msg:    db "Hello", 0 ; Zero is Null terminator 
    fmt:    db "%lf", 10, 0 ; printf format string follow by a newline(10) and a null terminator(0), "\n",'0'
    d1: dq 13.0
    d2: dq 15.0
    result : dq 0

SECTION .text
    global main

main:

    push rbp ; Push stack

      ; mov  rdi,fmt ; set the format for print
      ; mov rsi,msg ; set first parameter
      ; mov rax,1 ; one floating point
      ; movq xmm0, [d1]
      ; call printf

    call get_input 

    pop rbp     ; Pop stack
    mov rax,0   ; Exit code 0
    ret         ; Return


    get_input:
       mov  rdi,fmt ; set the format for print
       mov rsi,msg ; set first parameter
       mov rax,1 ; one floating point
       movq xmm0, [d1]
       call printf        
    ret

MAKE FILE:

nasm -g -f elf64 -F dwarf printf.s -o printf.o
gcc -g -Wall -o printf printf.o
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Alex Lavriv
  • 321
  • 1
  • 10
  • There's no C anywhere to be seen, so fixed the tags. – Deduplicator Apr 18 '18 at 12:23
  • 1
    I believe that printf is an external C function, so I am using gcc linker in order to make it work. – Alex Lavriv Apr 18 '18 at 12:24
  • Yes, `printf` is a part of the C and also the C++ standard library. It might also use the standard calling convention for C code on your platform, maybe it even was coded in C. Still, C is not relevant to your question as you don't use C. – Deduplicator Apr 18 '18 at 12:27

1 Answers1

1

The stack needs to be 16-byte aligned before calling printf.

It is aligned before the call to get_input, and the return address makes it misaligned, so get_input needs to subtract 8 to align it again.

prl
  • 11,716
  • 2
  • 13
  • 31