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
mov ebp, esp
sub esp, 4
mov eax, [ebp+8]
mov esi, [ebp+12]
add [ebp-4], eax
sub esi, 1
mov eax, [ebp-4]
add esp, 4
and this is the code for the exponent:
1 2 3 4 5 6 7 8 9 10 11
mov eax, [ebp+4] ; n
mov esi, [ebp+8] ; m
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.