x86 exponent problem

So I thought I would try to write a function in x86 that would give x^y given two integers x and y, while calling another function to do the multiplication. I seem to be running into a problem; my multiplication function seems to be working fine, but I can't seem to get the exponent function working; I keep getting large numbers that are clearly not the answer. Can anyone explain to me why the numbers are so wrong?
This is the code for the multiplication:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 product:
    push    ebp
    mov     ebp, esp
    push    esi
    sub     esp, 4
    mov     eax, [ebp+8]
    mov     esi, [ebp+12]
return:
    add     [ebp-4], eax
    sub     esi, 1
    jz      answer
    jmp     return
answer:
    
    mov     eax, [ebp-4]
    add     esp, 4
    pop     esi
    pop     ebp
    ret

and this is the code for the exponent:
1
2
3
4
5
6
7
8
9
10
11
exponent:
    mov     eax, [ebp+4]            ; n
    mov     esi, [ebp+8]            ; m
control:    
    dec     esi
    jz      solution
    call    product
    push    esi
    call    exponent
solution:
    ret
This is a C++ forum.

1. On line 5 you allocate a variable on the stack, but you never initialize it, so line 15 returns your answer plus random garbage. You could push 0.
2. [ebp - 4] is where you saved esi. The variable ended up at [ebp - 8].
3. Your exponent function is strange. It looks like you were initially going for an iterative implementation, but then lost faith halfway through and switched to a sort-of-but-not-quite recursive implementation. You push esi and then reload it in each recursive step, but you reuse eax throughout the recursion. I don't think I've ever seen code like this.
3. exponent doesn't respect the cdecl calling convention like product does. esi should be callee-saved.
Last edited on
Topic archived. No new replies allowed.