I have written a simple, basic swap function in asm in one file. In another file I have written a 'so-called' main program in order to test my swap function. However, as soon as the function is called, a segmentation fault occurs. I have no clue why this is happening.

global swap

;given two addresses of stack variables (rdi, rsi) swaps the content of the two
enter 0, 0

mov rax, [rdi] ;save of var1
mov rdx, [rsi] ;save of var2
mov rdi, rbx
mov rsi, rax 


The function receives the addresses of the two stack variables to swap in rdi and rsi; here is the code to test the function:

global _start
extern swap

section .text
enter 16, 0
mov qword [rbp], 0xFF
mov qword [rbp+8], 0x11

mov rdi, [rbp]
mov rsi, [rbp+8]
call swap  ;swap causes seg fault?? ------------------

    cmp qword [rbp], 0xFF
    jz FAIL
    cmp qword [rbp+8], 0x11
    jz FAIL
    cmp qword [rbp], 0x11
    jnz FAIL
    cmp qword [rbp+8], 0xFF
    jnz FAIL

;else success

mov rax, 60
xor rdi, rdi

    mov rax, 60
    mov rdi, -1

The segmentation fault occurs when I call the swap function. I suspect it has to do with accessing the stack of the main program, but I do not know how else this could be done. I also have a make file compiling and linking the files together (No problem there as far as I know)

0 Answers