I coded the following function in assembly:
.global my_pow
.type my_pow, @function
.data
format:
.asciz "%d\n"
.text
my_pow:
// Variable
pushq %rbp # value to print
pushq %rbx # i
movq $0x01, %rbp # value = 1
movl %edi, %ebx # i = number of iteration (1st arg)
loop:
movq $format, %rdi # 1st arg of printf is the format : "%d\n"
movq %rbp, %rsi # 2nd arg of printf is the value
xor %eax, %eax
call printf
cmp $0, %ebx # break if (i == 0)
je quit
addq %rbp, %rbp # value += value
subq $0x1, %rbx # i -= 1
jmp loop
quit:
// Deallocate stack
popq %rbp
popq %rbx
nop
ret
And when i run it with main. c:
#include <stdio.h>
extern int my_pow(int n);
int main(void) {
int n = 5;
my_pow(n);
return 0;
}
I got this output:
1
2
4
8
16
32
zsh: segmentation fault (core dumped) ./a.out
It seems that problem is in the quit section i dont why i get a segfault I use pop to deallocate the stack and then ret to return I compile with gcc -c my_pow.s and gcc my_pow.o main.c