Assembly x64 program intended to add two registers and print their sum results in a segmentation fault

Viewed 28

So I've been learning Assembly x86-64 with the AT&T Synthax for a couple of days now, and I've been trying to implement some programs to see how the instructions in Assembly work. I ended up with a segmentation fault when running the program built from the following code:

.text

.global main

main:
    #prologue
    pushq %rbp
    movq %rsp, %rbp

    movq $8, %rcx
    movq $15, %rbx
    addq %rcx, %rbx

    movq $0, %rax
    movq %rbx, %rdi
    call printf

    #epilogue
    movq %rbp, %rsp
    popq %rbp

end:
    movq $0, %rdi
    call exit

Basically, all I wanted to do by this was see how the add instruction works. I wrote the prologue and the epilogue of the main function correctly (I hope) and I also wrote the end of the program correctly (I hope x2). So I believe the part that might be wrong is in the actual main function. I was trying to make the registers RCX and RBX hold the decimal numbers 8 and 15 respectively, and then add RCX and RBX together. Finally, the program would then print the result (which was supposed to be in RBX). Spoiler alert? Segmentation fault.

I have two questions right now, which I couldn't manage to find the answers on the Internet to:

  1. What is wrong with the code I wrote that results in a segmentation fault? (Would it be the fact that I tried to add two registers together?)
  2. What exactly is a segmentation fault in assembly and how to avoid it?

Thank you in advance!

0 Answers
Related