2. Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
3. STACK AND HEAP
ARJUN S R
Arjun.sr007@gmail.com
www.facebook.com/arjun.a
ryavartham
twitter.com/arjun.sr007
in.linkedin.com/in/arjun.sr0
07
9745649882
4. PROGRAM ADDRESS SPACE
• Any program you run has, associated with it, some
memory which is divided into:
– Code Segment
– Data Segment (Holds Global Data)
– Stack (where the local variables and other temporary information is
stored)
– Heap
6. STACK
• Stack – a linear data structure in which items are added and
removed in last-in, first-out order.
• In most modern computer systems, each thread has a
reserved region of memory referred to as its stack.
• When a function executes, it may add some of its state data to
the top of the stack; when the function exits it is responsible
for removing that data from the stack.
• The place where arguments of a function call are stored
• The place where local data of called function is allocated
• Automatic data
7. • The place where called function leaves result for calling
function(return address).
• Supports recursive function calls.
• All modern programming languages require a stack.
• All modern processors provide a designated stack pointer
register.
• All modern process address spaces provide room for a stack
• It has mainly two operations
push-process of insert values into stack
pop –Process of remove a value from the stack
9. HEAP
• The heap is used to store variables dynamically
allocated by the application (malloc). The data
section initialized at compile-time.
• Dynamic variables are never initialized by the
compiler, so it is a good practice to initialize it.
Eg:
int *p;
p=new int;
*p=0;
10. • A place for allocating memory that is not part of last-
in, first-out discipline
• I.e., dynamically allocated data structures that
survive function calls
• E.g., strings in C
• new objects in C++, Java, etc.
• The size of the heap is set on application startup, but
can grow as space is needed (the allocator requests
more memory from the operating system)
• Used on demand to allocate a block of data for use
by the program.
11. HEAP AND STACK EXAMPLE
int main() {
pointT pt;
double total = 0.0;
pt.x = 1;
pt.y = 2;
int *array = new int[5];
Nonsense(array, pt, total);
return 0;
}
void Nonsense(int list[], pointT pt, double & sum) {
pointT *pptr = new pointT;
list[1] = pt.x;
sum += pt.y;
}
13. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
14. Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com