In The Name of Allah The Most Beneficent The Most Merciful: Subject: Data Structures & Algorithms
In The Name of Allah The Most Beneficent The Most Merciful: Subject: Data Structures & Algorithms
Lecture : 12
.globl _i_avg
_i_avg:
movl 4(%esp), %eax
addl 8(%esp), %eax # Add the args
sarl $1, %eax # Divide by 2
ret # Return value is in %eax
Memory Organization
Process 1
• When a program (browser)
(.exe) is run, it is Process 3
loaded in memory. It (word)
becomes a process.
Process 4
• The process is given (excel)
a block of memory. Process 2
• [Control-Alt-DEL] (dev-c++)
Windows OS
Task Manager
Memory Organization
Process 1
(browser)
Code
Process 3
(word) Static data
Process 4 Stack
(excel)
Process 2
(dev-c++)
Windows OS Heap
Stack Layout during a call
Here is stack layout when function F calls
function G:
Parameters(F) Parameters(F) Parameters(F)
Local variables(F) Local variables(F) Local variables(F)
Return address(G)
sp
At point of call During execution of G After call
Stack Applications…
• Finding Factorial
• Tower of Hanoi
• Stack use in compliers
– Translate infix expressions into some form of
postfix notation
– Translate postfix expression into machine code
AL 43
Tower of Hanoi
• The Tower of Hanoi (also called the Tower of Brahma is a
mathematical game or puzzle. It consists of three rods, and a number of
disks of different sizes which can slide onto any rod. The puzzle starts
with the disks in a neat stack in ascending order of size on one rod, the
smallest at the top, thus making a conical shape.
• The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
i. Only one disk can be moved at a time.
ii. Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
iii. No disk may be placed on top of a smaller disk.
• With three disks, the puzzle can be solved in seven moves. The minimum
number of moves required to solve a Tower of Hanoi puzzle is 2 n - 1,
AL 44
where n is the number of disks
Tower of Hanoi
AL 45
Underflow & Overflow
• When stack comes to its limit and yet another operation
tries to PUSH data onto the stack then a 'stack overflow'
occurs. When this happens it often causes the program to
crash. It is up to the software programmer to ensure that the
stack does not overflow.