Difference between revisions of "CSC231 Exercises On Functions"
Line 112: | Line 112: | ||
<br> | <br> | ||
Just go through the motion and draw the stack. Now the problem is that when the main program calls func1 the first time, the return address for the ellipses is pushed in the stack, then the processor starts executing the '''add eax,1''' function. Then it executes the '''call func2''' instruction and pushes the address of the '''add ebx,1''' instruction in the stack. Then, when it executes the '''ret''' instruction, the address of '''add ebx,1''' is popped out, and ebx is incremented by 1. Then the '''ret''' is executed and we return to the main function. The end result is that func1 is executed once, and func2 twice!</font> | Just go through the motion and draw the stack. Now the problem is that when the main program calls func1 the first time, the return address for the ellipses is pushed in the stack, then the processor starts executing the '''add eax,1''' function. Then it executes the '''call func2''' instruction and pushes the address of the '''add ebx,1''' instruction in the stack. Then, when it executes the '''ret''' instruction, the address of '''add ebx,1''' is popped out, and ebx is incremented by 1. Then the '''ret''' is executed and we return to the main function. The end result is that func1 is executed once, and func2 twice!</font> | ||
+ | |} | ||
+ | |||
+ | =Exercise 5= | ||
+ | Same question, but now observe that the programmer forgot the '''ret''' instruction at the end of the first function. | ||
+ | {| | ||
+ | ! width="300" | | ||
+ | ! width="300" | | ||
+ | |- | ||
+ | | | ||
+ | <code><pre> | ||
+ | mov eax, 0 | ||
+ | mov ebx, 0 | ||
+ | mov ecx, 10 | ||
+ | push ebx | ||
+ | for: call func1 | ||
+ | pop ebx | ||
+ | loop for | ||
+ | ... | ||
+ | |||
+ | func1: add eax, 1 | ||
+ | call func2 | ||
+ | ret | ||
+ | |||
+ | func2: add ebx, 1 | ||
+ | ret | ||
+ | </pre></code> | ||
+ | | | ||
+ | <font color="white"> | ||
+ | <br> | ||
+ | Because ebx is restored to its original value after the call to '''func1''', the loop does '''not''' modify ebx. | ||
+ | </font> | ||
|} | |} |
Revision as of 07:45, 8 October 2008
Back to Weekly Schedule.
Note: Highlight the white section on the right hand-side of each code section to see the solution.
Exercise 1
What is the behavior of this loop?
|
|
Exercise 2
Same question:
|
|
Exercise 3
Draw the stack as the processor executes this program:
|
|
Exercise 4
Same question, but now observe that the programmer forgot the ret instruction at the end of the first function.
|
|
Exercise 5
Same question, but now observe that the programmer forgot the ret instruction at the end of the first function.
|
|