0

I'm having trouble understanding why my code causes segmentation fault.

.section .rdata
format:
    .asciz "Hello world\n"

.text

.globl main

main:
    pushq %rbp
    leaq format(%rip), %rcx
    call printf
    popq %rbp
    ret

This is a simple assembly code that I wrote, and I compiiled using the following command using GCC in 64-bit windows.

gcc hello.s

After printing Hello world followed by a newline, the program crashes with Segmentation fault due to STATUS_ACCESS_VIOLATION. Is there anything wrong with my code?

  • 2
    Sorta looks like you are on Windows (both your calling convention and error code) trying to write a 64-bit program? We need to know your platform. If this is targeting Win64 then your lacking shadow space for 4 64-bit registers (32 bytes) prior to the call. https://msdn.microsoft.com/en-us/library/ms235286.aspx – Michael Petch Sep 21 '16 at 10:48
  • What happens if you put `sub $32, %rsp` just before the `call printf` and then `add $32, %rsp` right after the call? – Michael Petch Sep 21 '16 at 10:53
  • @MichaelPetch 16-byte stack alignment is also required (per https://msdn.microsoft.com/en-us/library/ew5tede7.aspx) but it's not clear to me whether that means %rsp is supposed to be aligned on entry to the callee, or immediately before the `call` instruction. Either way, your suggested offsets are not quite right. – zwol Sep 21 '16 at 12:59
  • 1
    Yes I know @Zwol however in this case he happens to be 16 byte aligned because `main` was misaligned by the return address on the stack and the `push %rbp` aligned back to 16-bytes. So subtracting 32 from that is of course still aligned. At function call it is aligned. But after control is transferred the call misaligns by 8. Push of one 64-bit register realigns to 16. Had the PUSH not been there then I would have complained about alignment. – Michael Petch Sep 21 '16 at 13:06
  • 1
    @MichaelPetch Oh, OK. I think I was doing the math for 32-bit mode in my head without realizing it. – zwol Sep 21 '16 at 13:09
  • 1
    the posted code is not `C`, so please remove the `c` tag – user3629249 Sep 22 '16 at 15:50

0 Answers0