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?

6
  • 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. msdn.microsoft.com/en-us/library/ms235286.aspx Commented Sep 21, 2016 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? Commented Sep 21, 2016 at 10:53
  • 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. Commented Sep 21, 2016 at 13:06
  • 1
    @MichaelPetch Oh, OK. I think I was doing the math for 32-bit mode in my head without realizing it. Commented Sep 21, 2016 at 13:09
  • 1
    the posted code is not C, so please remove the c tag Commented Sep 22, 2016 at 15:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.