
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Proper stack and heap usage in C++?
The stack − All variables declared inside the function will take up memory from the stack. So, any local variable inside a function lives on the stack.
The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. So If we want something to live longer than the function that declared it, we must allocate it on the heap.
Example
int main() { int a; //get memory allocated on stack. int *ptr=new int[7]; //memory for 7 integers allocated on heap. }
The main issue in heap memory is fragmentation whereas memory shortage problem is seen more likely in stack. Memory size can be changed in heap which can’t be changed in stack.
- Related Articles
- Heap overflow and Stack overflow in C
- Heap overflow and Stack overflow
- Difference Between Stack and Heap
- Global memory management in C++ : Stack or Heap?
- Difference between Stack and Heap memory in Java
- stack empty() and stack size() in C++ STL
- Convert min Heap to max Heap in C++
- Stack and Queue in C#
- Heap Sort in C#
- Binomial Heap in C++?
- stack push() and pop() in C++ STL
- Stack Class in C#
- Stack Unwinding in C++
- Maximum element in min heap in C++
- Convert BST to Max Heap in C++

Advertisements