0% found this document useful (0 votes)
109 views9 pages

Stack Vs Heap Memory Allocation: Memory Layout of C Program

Uploaded by

Chandan Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views9 pages

Stack Vs Heap Memory Allocation: Memory Layout of C Program

Uploaded by

Chandan Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python

Stack vs Heap Memory Allocation


Difficulty Level :
Easy ● Last Updated :
21 Jun, 2021

Memor y in a C/C++/Java program can either be allocated on a stack or a heap.

Prerequisite: Memor y layout of C program.

Stack Allocation: The allocation happens on contiguous blocks of memor y. We call it a

stack memor y allocation because the allocation happens in the function call stack. The

size of memor y to be allocated is known to the compiler and whenever a function is

called, its variables get memor y allocated on the stack. And whenever the function

call is over, the memor y for the variables is de-allocated. This all happens using some

predefined routines in the compiler. A programmer does not have to worr y about

memor y allocation and de-allocation of stack variables. This kind of memor y

allocation also known as Temporar y memor y allocation because as soon as the

method finishes its execution all the data belongs to that method flushes out from the

stack automatically. Means, any value stored in the stack memor y scheme is

accessible as long as the method hasn’t completed its execution and currently in

running state.

Key Points :

It ’s a temporar y memor y allocation scheme where the data members are

accessible only if the method( ) that contained them is currently is running.

It allocates or de-allocates the memor y automatically as soon as the corresponding

method completes its execution.

We receive the corresponding error Java. lang. StackOverFlowError by JVM, If the

stack memor y is filled completely.

Stack memor y allocation is considered safer as compared to heap memor y

allocation because the data stored can only be access by owner thread.

Memor y allocation and de-allocation is faster as compared to Heap-memor y

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
allocation.
you have read and understood our
Cookie Policy &
Privacy Policy
Stack-memor y has less storage space as compared to Heap-memor y.
Got It !

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 1/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

CPP

int main()
{
   // All these variables get memory
   // allocated on stack
   int a;
   int b[10];
   int n = 20;
   int c[n];
}

Heap Allocation: The memor y is allocated during the execution of instructions written

by programmers. Note that the name heap has nothing to do with the heap data

structure. It is called heap because it is a pile of memor y space available to

programmers to allocated and de-allocate. Ever y time when we made an object it

always creates in Heap-space and the referencing information to these objects are

always stored in Stack-memor y. Heap memor y allocation isn’t as safe as Stack

memor y allocation was because the data stored in this space is accessible or visible to

all threads. If a programmer does not handle this memor y well, a memor y leak can

happen in the program.

The Heap-memor y allocation is fur ther divided into three categories :- These three

categories help us to prioritize the data(Objects) to be stored in the Heap-memor y or

in the Garbage collection.

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
Young Generation – It ’s the por tion of the memor y where all the new data(objects)
you have read and understood our
Cookie Policy &
Privacy Policy
are made to allocate the space and whenever this memor y is completely filled then
Got It !
the rest of the data is stored in Garbage collection.

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 2/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

Old or Tenured Generation – This is the par t of Heap-memor y that contains the

older data objects that are not in frequent use or not in use at all are placed.

Permanent Generation – This is the por tion of Heap-memor y that contains the

JVM’s metadata for the runtime classes and application methods.

Key Points :

We receive the corresponding error message if Heap-space is entirely full,  java.

lang.OutOfMemor yError by JVM.

This memor y allocation scheme is different from the Stack-space allocation, here

no automatic de-allocation feature is provided. We need to use a Garbage collector

to remove the old unused objects in order to use the memor y efficiently.

The processing time(Accessing time) of this memor y is quite slow as compared to

Stack-memor y.

Heap-memor y is also not threaded-safe as Stack-memor y because data stored in

Heap-memor y are visible to all threads.

Size of Heap-memor y is quite larger as compared to the Stack-memor y.

Heap-memor y is accessible or exists as long as the whole application(or java

program) runs.

CPP

int main()
{
   // This memory for 10 integers
   // is allocated on heap.
   int *ptr  = new int[10];
}

Intermixed example of both kind of memor y allocation Heap and Stack in java:

Java

class Emp {
    int id;
    String emp_name;
 
    public Emp(int id, String emp_name) {
        this.id = id;
        this.emp_name
We use cookies to ensure you have the=best
emp_name;
browsing experience on our website. By using our site, you
acknowledge that
    } you have read and understood our
Cookie Policy &
Privacy Policy
}
  Got It !

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 3/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

public class Emp_detail {


    private static Emp Emp_detail(int id, String emp_name) {
        return new Emp(id, emp_name);
    }
 
    public static void main(String[] args) {
        int id = 21;
        String name = "Maddy";
        Emp person_ = null;
        person_ = Emp_detail(id, emp_name);
    }
}

Following are the conclusions on which we’ll make after analyzing the above

example :

A s we star t execution of the have program, all the run-time classes are stored in

the Heap-memor y space.

Then we find the main() method in the next line which is stored into the stack along

with all it ’s primitive(or local) and the reference variable Emp of type Emp_detail

will also be stored in the Stack and will point out to the corresponding object stored

in Heap memor y.

Then the next line will call to the parameterized constructor Emp(int, String) from

main( ) and it ’ll also allocate to the top of the same stack memor y block. This will

store:

The object reference of the invoked object of the stack memor y.

The primitive value(primitive data type) int id in the stack memor y.

The reference variable of String emp_name argument which will point to the

actual string from string pool into the heap memor y.

Then the main method will again call to the Emp_detail() static method, for which

allocation will be made in stack memor y block on top of the previous memor y

block.

So, for the newly created object Emp of type Emp_detail and all instance variables

will be stored in heap memor y.

Pictorial representation as shown in the Figure.1 below:

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
you have read and understood our
Cookie Policy &
Privacy Policy

Got It !

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 4/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

Fig.1

Key Differences Between Stack and Heap Allocations 

1. In a stack, the allocation and de-allocation are automatically done by the compiler

whereas in heap, it needs to be done by the programmer manually.

2. Handling of Heap frame is costlier than the handling of the stack frame.

3. Memor y shor tage problem is more likely to happen in stack whereas the main issue

in heap memor y is fragmentation.

4. Stack frame access is easier than the heap frame as the stack have a small region of

memor y and is cache-friendly, but in case of heap frames which are dispersed

throughout the memor y so it causes more cache misses.

5. A stack is not flexible, the memor y size allotted cannot be changed whereas a heap

is flexible, and the allotted memor y can be altered.

6. Accessing time of heap takes is more than a stack.

Comparison Char t

Parameter STACK HE AP

Basic Memor y is allocated in a Memor y is allocated in any

contiguous block. random order.

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
you have read and understood our
Cookie Policy &
Privacy Policy
Allocation and Automatic by compiler Manual by the programmer.

De-allocation instructions.
Got It !

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 5/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

Parameter STACK HE AP

Cost Less More

Implementation Easy Hard

Access time Faster Slower

Main Issue Shor tage of memor y Memor y fragmentation

Locality of Excellent Adequate

reference

Safety Thread safe, data stored can only Not Thread safe, data stored

be accessed by owner visible to all threads

Flexibility Fixed-size Resizing is possible

Data type Linear Hierarchical

structure

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
you have read and understood our
Cookie Policy &
Privacy Policy

Got It !

133
https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/
Lik 6/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

Like 133

Next

Memory Layout of C Programs

RECOMMENDED ARTICLES Page : 1 2 3

Difference between Static Difference between Static and


01 05
Allocation and Heap Allocation Dynamic Memory Allocation in C
31, Mar 20 18, Aug 20

Difference between Static


02
allocation and Stack allocation Difference between Min Heap and
06
31, Mar 20
Max Heap
06, Nov 20

Difference between Binary Heap,


03
Binomial Heap and Fibonacci
Heap Memory representation of
07
02, Nov 20
Binomial Heap
02, Nov 18

Difference between Contiguous


04
and Noncontiguous Memory
Allocation Heap overflow and Stack overflow
21, Apr 20
08 25, Feb 18

Ar ticle Contributed By :

Ankit_Bisht
@Ankit_Bisht

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
Vote for difficulty
you have read and understood our
Cookie Policy &
Privacy Policy
Current difficulty :
Easy

Got It !
Easy Normal Medium Hard Expert
https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 7/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks
Easy Normal Medium Hard Expert

Improved By : ShubhamKatta, ashushrma378, madhav_mohan, SagarPawar,


shubhamsharma8337, nehasagar144, dev6251

Article Tags : system-programming, Technical Scripter 2018, Difference Between,


Technical Scripter

Improve Article Report Issue

Writing code in comment?


Please use ide.geeksforgeeks.org,
generate link and share the link here.

Load Comments

5th Floor, A-118,

Sector-136, Noida, Uttar Pradesh - 201305


[email protected]

Company Learn
About Us Algorithms
Careers Data Structures
Privacy Policy Languages
Contact Us CS Subjects
Copyright Policy Video Tutorials

Web Development Contribute


Web
We use cookies to ensure youTutorials Writeouran
have the best browsing experience on our website. By using Article
site, you
acknowledge that
you have read and understood our
Cookie Policy &
Privacy Policy
HTML Write Interview Experience
Got It !
CSS Internships
https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 8/9
28/11/2021, 09:55 Stack vs Heap Memory Allocation - GeeksforGeeks

JavaScript Videos
Bootstrap

@geeksforgeeks
, Some rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that
you have read and understood our
Cookie Policy &
Privacy Policy

Got It !

https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ 9/9

You might also like