Lecture No.13
Lecture No.13
7th Edition
Kip R. Irvine
(c) Pearson Education, 2014. All rights reserved. You may modify and copy this slide show for your personal use, or for
use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.
Chapter Overview
• Stack Frames
• Recursion
.data
val1 DWORD 5 (val2) 6
val2 DWORD 6 (val1) 5 ESP
.code
push val2
push val1
Stack prior to CALL
.code
push OFFSET val2
push OFFSET val1 Stack prior to CALL
.data
count = 100
array WORD count DUP(?)
.code
push OFFSET array
push COUNT
call ArrayFill
ArrayFill PROC
push ebp offset(array) [EBP + 12]
mov ebp,esp
count
pushad [EBP + 8]
mov esi,[ebp+12] return address
mov ecx,[ebp+8] EBP EBP
.
.
ESI points to the beginning of the array, so it's easy to use a loop
to access each array element. View the complete program.
1 BP in Real-address mode
pop ebp
ret 8
Difference PROC
push ebp
mov ebp,esp
mov eax,[ebp + 8] ; second argument
sub eax,[ebp + 12] ; first argument
pop ebp
ret 8
Difference ENDP
MySub PROC
push ebp
mov ebp,esp
push ecx ; save local registers
push edx
pop edx
pop ecx
ret
• What is Recursion?
• Recursively Calculating a Sum
• Calculating a Factorial
E B
D C
{ 5! = 5 * 4! 5 * 24 = 120
if(n == 0)
return 1; 4! = 4 * 3! 4 * 6 = 24
else
return n * factorial(n-1); 3! = 3 * 2! 3*2=6
}
2! = 2 * 1! 2*1=2
Factorial PROC
push ebp
mov ebp,esp
mov eax,[ebp+8] ; get n
cmp eax,0 ; n < 0?
ja L1 ; yes: continue
mov eax,1 ; no: return 1
jmp L2
L1: dec eax
push eax ; Factorial(n-1)
call Factorial
; Instructions from this point on execute when each
; recursive call returns.
ReturnFact:
mov ebx,[ebp+8] ; get n
mul ebx ; eax = eax * ebx
L2: pop ebp ; return EAX
ret 4 ; clean up stack
Factorial ENDP