Why Linked List is implemented on Heap memory rather than Stack memory?

05 Jul, 2022
Pre-requisite: 
Linked List Data StructureStack vsHeap Memory Allocation
The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind it.
Stack vs Heap Memory
The computer’s memory is divided into heap and stack memory segments. Stack memory segment is relatively small so it is mainly used for operations like recursion or control jump statements like goto statement. Due to the small size of the stack segment, it is not used for deep recursion levels as it may throw a stack overflow error.
On the other hand, a linked list has the major advantage of dynamically expanding itself when needed without worrying about memory consumption. This is the reason why heap is preferred for storing linked list-object.
Why linked list is not stored in stack memory?
The question of why one cannot make a linked list with stack memory is due to the scope rules and automatic memory management on the stack. The basic idea of a linked list is to link nodes together based on their memory address. If each node is created on the stack then those nodes will be deleted after they go out of scope, so even if the user keeps pointers to their memory address it is not safe to assume that they won’t be overwritten by something else.
The linked list can be implemented on the stack memory as well. Below is the C++ implementation of creating a linked list in stack memory:
C++
Java
C#
Javascript
// C++ program to implement// linked list in stack#include <iostream>using namespace std; // Structure of the linked liststruct Node {    int data;    struct Node* next;     // Constructor    Node(int x)    {        data = x;        next = NULL;    }}* head = NULL; // Function to print the linked listvoid printLinkedList(Node* head){    struct Node* temp = head;     // Traversing linked list    while (temp) {        cout << temp->data << " ";        temp = temp->next;    }} // Driver codeint main(){    // Creation of linked list in stack    struct Node first = Node(1);    struct Node second = Node(2);    struct Node third = Node(3);    struct Node fourth = Node(4);     head = &first;     // 1 -> 2 -> 3 -> 4    first.next = &second;    second.next = &third;    third.next = &fourth;    fourth.next = NULL;     // Printing the elements of    // a linked list    printLinkedList(head);     return 0;}
// Java program to implement// linked list in stack import java.util.*; class GFG{ // Structure of the linked liststatic class Node {    int data;    Node next;     // Constructor    Node(int x)    {        data = x;        next = null;    }};static Node head = null; // Function to print the linked liststatic void printLinkedList(Node head){    Node temp = head;     // Traversing linked list    while (temp!=null) {        System.out.print(temp.data+ " ");        temp = temp.next;    }} // Driver codepublic static void main(String[] args){    // Creation of linked list in stack    Node first = new Node(1);    Node second = new  Node(2);    Node third = new Node(3);    Node fourth = new Node(4);     head = first;     // 1.2.3.4    first.next = second;    second.next = third;    third.next = fourth;    fourth.next = null;     // Printing the elements of    // a linked list    printLinkedList(head); }} // This code contributed by shikhasingrajput
// C# program to implement// linked list in stackusing System;using System.Collections.Generic; public class GFG{   // Structure of the linked list  class Node {    public int data;    public Node next;     // Constructor    public Node(int x)    {      data = x;      next = null;    }  };  static Node head = null;   // Function to print the linked list  static void printList(Node head)  {    Node temp = head;     // Traversing linked list    while (temp!=null) {      Console.Write(temp.data+ " ");      temp = temp.next;    }  }   // Driver code  public static void Main(String[] args)  {     // Creation of linked list in stack    Node first = new Node(1);    Node second = new  Node(2);    Node third = new Node(3);    Node fourth = new Node(4);     head = first;     // 1.2.3.4    first.next = second;    second.next = third;    third.next = fourth;    fourth.next = null;     // Printing the elements of    // a linked list    printList(head);   }} // This code is contributed by shikhasingrajput
<script>// Javascript program to implement// linked list in stack // Structure of the linked listclass Node {     // Constructor    constructor(x) {        this.data = x;        this.next = null;    }} // Function to print the linked listfunction printLinkedList(head) {    let temp = head;     // Traversing linked list    while (temp) {        document.write(temp.data + " ");        temp = temp.next;    }} // Driver code // Creation of linked list in stacklet first = new Node(1);let second = new Node(2);let third = new Node(3);let fourth = new Node(4); head = first; // 1 -> 2 -> 3 -> 4first.next = second;second.next = third;third.next = fourth;fourth.next = null; // Printing the elements of// a linked listprintLinkedList(head); // This code is contributed by gfgking.</script>
Output:
1 2 3 4 
Condition when linked list implementation on the stack will not work:
The above code won’t work if we write the logic of the creation of a linked list in a separate function and the logic of printing the elements of the linked list in a separate function. Below is its C++ implementation of the above concept:
C++
Java
C#
Javascript
// C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node {    int data;    struct Node* next;     Node(int x)    {        data = x;        next = NULL;    }}* head = NULL; // Function to return the head pointer// of the created linked listNode* CreateLinkedList(){    struct Node first = Node(1);    struct Node second = Node(2);    struct Node third = Node(3);    struct Node fourth = Node(4);     head = &first;     // 1->2->3->4    first.next = &second;    second.next = &third;    third.next = &fourth;    fourth.next = NULL;     return head;} // Function to print the linked listvoid printLinkedList(Node* head){    struct Node* temp = head;     // Traversing linked list    while (temp) {        cout << temp->data << " ";        temp = temp->next;    }} // Driver Codeint main(){    struct Node* head = CreateLinkedList();    printLinkedList(head);    return 0;}
// Java program to implement// the above approach import java.util.*; class GFG{ // Structure of the linked liststatic class Node {    int data;    Node next;     Node(int x)    {        data = x;        next = null;    }}static Node head = null; // Function to return the head pointer// of the created linked liststatic Node CreateLinkedList(){    Node first = new Node(1);    Node second = new Node(2);    Node third = new Node(3);    Node fourth = new Node(4);     head = first;     // 1.2.3.4    first.next = second;    second.next = third;    third.next = fourth;    fourth.next = null;     return head;} // Function to print the linked liststatic void printLinkedList(Node head){    Node temp = head;     // Traversing linked list    while (temp!=null) {        System.out.print(temp.data+ " ");        temp = temp.next;    }} // Driver Codepublic static void main(String[] args){    Node head = CreateLinkedList();    printLinkedList(head);}} // This code is contributed by 29AjayKumar
// C# program to implement// the above approach using System; public class GFG{   // Structure of the linked list  class Node {    public int data;    public Node next;     public Node(int x)    {      data = x;      next = null;    }  }  static Node head = null;   // Function to return the head pointer  // of the created linked list  static Node CreateList()  {    Node first = new Node(1);    Node second = new Node(2);    Node third = new Node(3);    Node fourth = new Node(4);     head = first;     // 1.2.3.4    first.next = second;    second.next = third;    third.next = fourth;    fourth.next = null;     return head;  }   // Function to print the linked list  static void printList(Node head)  {    Node temp = head;     // Traversing linked list    while (temp != null) {      Console.Write(temp.data + " ");      temp = temp.next;    }  }   // Driver Code  public static void Main(String[] args)  {    Node head = CreateList();    printList(head);  }} // This code is contributed by shikhasingrajput
<script> // javascript program to implement// the above approach    // Structure of the linked list     class Node     {        constructor( x) {            this.data = x;            this.next = null;        }    }     var head = null;     // Function to return the head pointer    // of the created linked list    function CreateLinkedList() {        var first = new Node(1);        var second = new Node(2);        var third = new Node(3);        var fourth = new Node(4);         head = first;         // 1.2.3.4        first.next = second;        second.next = third;        third.next = fourth;        fourth.next = null;         return head;    }     // Function to print the linked list    function printLinkedList( head) {        var temp = head;         // Traversing linked list        while (temp != null) {            document.write(temp.data + " ");            temp = temp.next;        }    }     // Driver Code        var head = CreateLinkedList();        printLinkedList(head);         // This code contributed by shikhasingrajput</script>
Explanation:
The above code gives the verdict as SEGMENTATION FAULT. The reason behind it is that during the creation of the linked list in the stack memory, all the objects created by a function will be disappeared as the stack frame is popped whenever the function ends or returns. Refer to this article to know the reason behind the popping of stack frame whenever function ends.
Why linked list is stored in heap memory?
In a linked list, when there is a need to store more data, we can allocate the memory at run-time by using malloc or a new function in C/ C++. So dynamic memory allocation reserve size from heap area, therefore, a linked list is stored in heap memory.If there is a need to store linked lists in the stack area then implement linked lists without using malloc or a new function.
Below is the C++ program to show how to implement a linked list in heap memory without throwing segmentation fault error:
C++
Java
C#
Javascript
// C++ program to implement// the above approach#include <iostream>using namespace std; // Structure of the linked liststruct Node {    int data;    struct Node* next;};struct Node* head = NULL; // Function to create nodes of// the linked listvoid CreateLinkedList(int new_data){    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));    new_node->data = new_data;    new_node->next = head;    head = new_node;} // Function to print the linked listvoid printLinkedList(){    struct Node* temp;    temp = head;     // Traversing linked list    while (temp != NULL) {        cout << temp->data << " ";        temp = temp->next;    }} // Driver Codeint main(){    CreateLinkedList(1);    CreateLinkedList(2);    CreateLinkedList(3);    CreateLinkedList(4);    printLinkedList();    return 0;}
// Java program to implement// the above approachimport java.util.*;public class GFG{ // Structure of the linked liststatic class Node {    int data;    Node next;};static Node head = null; // Function to create nodes of// the linked liststatic void CreateLinkedList(int new_data){    Node new_node = new Node();    new_node.data = new_data;    new_node.next = head;    head = new_node;} // Function to print the linked liststatic void printLinkedList(){    Node temp;    temp = head;     // Traversing linked list    while (temp != null) {        System.out.print(temp.data+ " ");        temp = temp.next;    }} // Driver Codepublic static void main(String[] args){    CreateLinkedList(1);    CreateLinkedList(2);    CreateLinkedList(3);    CreateLinkedList(4);    printLinkedList();}} // This code is contributed by 29AjayKumar
// C# program to implement// the above approachusing System;using System.Collections.Generic; public class GFG {   // Structure of the linked list  public class Node {    public int data;    public Node next;  };   static Node head = null;   // Function to create nodes of  // the linked list  static void CreateList(int new_data) {    Node new_node = new Node();    new_node.data = new_data;    new_node.next = head;    head = new_node;  }   // Function to print the linked list  static void printList() {    Node temp;    temp = head;     // Traversing linked list    while (temp != null) {      Console.Write(temp.data + " ");      temp = temp.next;    }  }   // Driver Code  public static void Main(String[] args) {    CreateList(1);    CreateList(2);    CreateList(3);    CreateList(4);    printList();  }} // This code is contributed by umadevi9616
<script>// javascript program to implement// the above approach     // Structure of the linked list     class Node {         constructor(){        this.data = 0;        this.next = null;    }    }    var head = null;     // Function to create nodes of    // the linked list    function CreateLinkedList(new_data)    {        var new_node = new Node();        new_node.data = new_data;        new_node.next = head;        head = new_node;    }     // Function to print the linked list    function printLinkedList()    {        var temp;        temp = head;         // Traversing linked list        while (temp != null) {            document.write(temp.data + " ");            temp = temp.next;        }    }     // Driver Code        CreateLinkedList(1);        CreateLinkedList(2);        CreateLinkedList(3);        CreateLinkedList(4);        printLinkedList(); // This code is contributed by umadevi9616</script>
Output:
4 3 2 1
Linked list in Stack vs Heap Memory
sweetyty
gfgking
shikhasingrajput
29AjayKumar
umadevi9616
sagartomar9927
surinderdawra388
memory-management
Data Structures
Heap
Linked List
Stack
Data Structures
Linked List
Stack
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Hashing | A Complete Tutorial
What is Data Structure: Types, Classifications and Applications
TCS NQT Coding Sheet
Find if there is a path between two vertices in an undirected graph
HeapSort
K'th Smallest/Largest Element in Unsorted Array | Set 1
Binary Heap
Introduction to Data Structures
Huffman Coding | Greedy Algo-3