cassemblynasmfactorial

Recursive Factorial of a number using C and NASM


I am trying to find the factorial of a user input number, and display it.

The issue I am facing is that no mater what the input, output is always 1.

wrong output

The input and output part is done through the C language, as in the code below,

#include <stdio.h>

extern int factorial(int n);

int main() {
    int n, res;

    printf("Enter a number: ");
    scanf("%d", &n);

    res = factorial(n);

    printf("Factorial of %d is: %d\n", n, res);
    return 0;
}

and the NASM code containing the logic for the factorial code is as follows,

section .text
    global factorial

factorial:
    ; Input:  ecx

    ; Base case
    cmp ecx, 1
    jbe .base_case    

    ; Recursive case
    push ecx ;save n in stack

    ; Recurcive call with n-1
    dec ecx
    call factorial

    pop ecx ;pop from stack

    imul eax, ecx

    ret

.base_case:
    mov eax,1
    ret

For better understanding of the code, I have added comments.

And the command I am using to compile this is as follows nasm -f elf RecurciveFactorial.asm && gcc -m32 -o RecurciveFactorial RecurciveFactorial.c RecurciveFactorial.o && ./RecurciveFactorial

I have tried changing the jbe to jle and changing the order of imul, i.e., imul eax,ecx to imul ecx,eax, and also initialize the eax register with value 1, but that also dosen't work.

I am also getting this warning - warning

This is my first time doing the linking of C and NASM. The factorial is being called in the C code, I have tested that part as well.

Help would be highly appreciated, and also tell me whether the warning is of importance or can be ignored.


Solution

  • The first function arg is pass by rdi register not rcx.

    You have high chance to have 0 at base value in ecx, and that jump on base_case, where you move the 1 to rax register you recv.

    You can check here the usage of all register