Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Difference Between Stack-Allocated and Heap-Allocated Arrays
Next article icon

Difference Between Stack-Allocated and Heap-Allocated Arrays

Last Updated : 03 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C/C++, arrays can be allocated in two areas of memory: the stack and the heap. Each has its own characteristics and use cases. In this article, we will see the key differences between stack-allocated and heap-allocated arrays.

Stack-Allocated Arrays

The arrays declared as static arrays in the function or program are called stack-allocated arrays. These arrays are stored on the program's call stack and the memory for stack-allocated arrays is allocated and deallocated automatically as the program enters and exits the scope where the array is declared. Stack-allocated arrays have a limited lifetime tied to the scope in which they are declared and cannot change its size once they are declared. Once the program exits the scope, the memory allocated for stack-allocated arrays is automatically reclaimed.

Syntax

DataType array_name[array_size]

Example

The below example demonstrates how the array is allocated on the stack within the function's scope and once the function returns, the memory allocated for the array is automatically deallocated.

C++
// C++ Program for stack allocated array  #include <iostream> using namespace std;  int main() {      // Initializing a stack-allocated  array     int stackArray[5] = { 1, 2, 3, 4, 5 };     // Printing the elements of the stack     cout << "Stack-allocated array elements: ";     for (int i = 0; i < 5; ++i) {         cout << stackArray[i] << " ";     }     return 0; } 

Output
Stack-allocated array elements: 1 2 3 4 5 

Heap-Allocated Arrays

Heap-allocated arrays are stored on the heap, a region of memory separate from the stack. Memory for heap-allocated arrays is manually allocated and deallocated using functions like new and delete operators.

Syntax

data_type* array_name = new data_type[array_size]

Example

The below example demonstrates how the array is allocated on the heap using the new operator. Memory allocated on the heap persists until it is explicitly deallocated using delete[] keyword.

C++
// C++ Program for Heap-Allocated Arrays  #include <iostream> using namespace std;  int main() {      // Initializing a heap-allocated array     int* heapArray = new int[5]{ 1, 2, 3, 4, 5 };      // Printing the elements of heap allocated array     cout << "Heap-allocated array elements: ";     for (int i = 0; i < 5; ++i) {         cout << heapArray[i] << " ";     }     cout << endl;     // Deallocate memory allocated on the heap     delete[] heapArray;     return 0; } 

Output
Heap-allocated array elements: 1 2 3 4 5   

Difference Between Stack-Allocated and Heap-Allocated Arrays

The following table illustrates the key differences between stack-allocated and heap-allocated arrays.

ParameterStack Allocated Arrays Heap Allocated Arrays
BasicMemory is allocated in a contiguous block.Memory is allocated in any random order.
Allocation and De-allocationAutomatic by compiler instructions.Manually by the programmer.
CostLessMore
ImplementationStraightforward and managed by the compiler.Explicit managed by the programmer
Access timeFasterSlower
Main IssueShortage of memoryMemory fragmentation
Locality of referenceExcellentAdequate
SafetyThread safe, data stored can only be accessed by the owner.Not Thread safe, data stored visible to all threads.
FlexibilityFixed-size.Resizing is possible.
Data type structureLinearHierarchical
PreferredStatic memory allocation is preferred in an array.Heap memory allocation is preferred in the linked list.
SizeSmall than heap memory.Larger than stack memory.

Next Article
Difference Between Stack-Allocated and Heap-Allocated Arrays

A

abhay94517
Improve
Article Tags :
  • C++ Programs
  • C++
  • c-array
  • cpp-array
  • C-Arrays
  • C-Dynamic Memory Allocation
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

    Difference Between Pointers and Array Notations in C++
    In C++, pointers and array notations are two ways using which we work with arrays and memory for accessing the data. They have distinct behaviours and are used in different contexts. In this article, we will learn the key differences between pointers and array notations in C++. Difference Between Po
    4 min read
    Difference between int (*p)[3] and int* p[3]?
    Pointers store the address of variables or a memory location. Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format: Syntax: datatype *var_na
    2 min read
    Different ways of accessing array elements in C++
    In this article, two unique and different ways of accessing an element from an array rather than the conventional arr[i] expression are discussed below. Using pointer *(arr+1)Using a little manipulation i[arr] for using arrays and the reason behind that. When a C++ program is compiled, a symbol tabl
    4 min read
    How to Create a Stack of Arrays in C++?
    In C++, the std::stack is a container that follows the LIFO (Last In, First Out) rule, whereas std::array is a sequence container that stores elements in contiguous memory. In this article, we will learn how to create a stack of an array in C++. Example: Input: arr1 = {1, 2, 3}; arr2 = {4, 5, 6}; ar
    2 min read
    Why global array has a larger size than the local array?
    An array in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using array indices. It can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. For
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All 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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences