Pointers and Dynamic Memory - Stack vs Heap
How is memory from a computer programmer stored in the computer Architeture?
#include <iostream>
using std::cout;
using std::endl;
int total;
int Square(int x)
{
return x*x;
}
int SquareOfSum(int x, int y)
{
int z = Square(x+y);
return z;
}
int main()
{
int a = 4, b = 8;
total = SquareOfSum(a,b);
cout << "Output: " << total << endl;
}
What happens in the memory when the code above is executed?
Heap vs Stack in Dynamic Memory
If we have a scenario like we have to decide how large the array will be based on some paramter during runtime then it is a problem with stack.
For all these requirements like allocating large chunk of memory or keeping variable in the memory till the time we want, we have heap
Unlike stack, Heap size is not fixed and its size can vary during the lifetime of the application and there is not rule for allocation or deallocation of the memory. We as programmers can control how much memory to use from the heap till what to keep the data in the memory during the application lifetime.
You can look at Heap as one large free pool of memory available to us that we can use flexibly as per our need.
Heap is also called Dynamic Memory Allocation
Note: Heap is also a Data Structure, I’ve covered in a little in Python, in my Data Structures and Algorithms page!
Example of Using Heap
Any memory which is allocated using the new keyword is cleared off the Heap by calling the delete keyword.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int a; // Goes on Stack
int *p;
p = new int;
*p = 10;
delete p;
p = new int;
*p = 20;
}
We can control when to free anything on the Heap
If we wanted tro store an Array on the Heap, then all we need to do is to use the new keyword and pass the size of the Array need.
We get the Base Address of the Array. See example below:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
p = new int[20];
delete p;
}
If new is not able to find any free block of memory, it’s not able to allocate any memory on the Heap it returns NULL. So for error handling we need to this and we need to write code correct.
Notes