C++ Stack vs Heap

chuuuing
4 min readMar 26, 2021

--

Stack and Heap are 2 areas we have in our RAM.

  • Stack Allocation (a.k.a. Temporary Memory Allocation) — stores local variables, pointers to the local variables
  • Heap Allocation — stores global variables

1 min take away

Stack

Stack is called stack because it's like a “stack of papers”, you can put or get something on top, but you can’t put anything in the middle or bottom.

However, it is possible to assess or modify the value of every paper.

  • the memory for the variable is allocated when its function is called
  • the memory for the variable is deallocated automatically whenever the function call is over
  • the data is ONLY accessible to the current thread
  • faster than Heap
  • safer than Heap (due to the accessibility)
  • less storage compare to Heap
  • contiguous storage in memory
int value = 5;int array[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
struct Vector3 {
float x,y,z;
Vector3(): x(20), y(21), z(23) {} // default value
};
Vector3 vector;
Memory view of &value
Memory view of &array
Memory view of &vector

Address of &value: 0x00007ffee46c48a0
Address of &array: 0x00007ffee46c48b0
Address of &vector: 0x00007ffee46c48980

Heap

The memory is allocated during the execution of instructions written by programmers.

  • No automatic deallocation, need to be done manually
  • Heap exists as long as the whole application runs
  • objects are created in Heap
  • the data is accessible to all threads
  • slower than Stack
  • larger storage than Stack
  • random-fragmented storage in memory (distributed, not continuous)

Allocates memory

Heap uses the keyword “new” to declare variable, in other words, it declares a pointer to allocates memory.

The “new” calls function “malloc()” which calls the operation-system-specific function, which will allocate memory for you on the Heap.

Roles of malloc():

  • Tracks and bookkeeps block status in the Heap
  • Allocates data on a free block that has enough space
  • Returns a pointer to the beginning of the block.

1) integer on Heap:

int* hvalue = new int;
*hvalue = 5;
// or in oneline:
int* hvalue = new int(5);
Memory view of hvalue

2) array on Heap:

int *harray = new int[5];
harray[0] = 1;
harray[1] = 2;
harray[2] = 3;
harray[3] = 4;
harray[4] = 5;
Memory view of harray

3) vector on Heap:

struct Vector3 {
float x,y,z;
Vector(): x(20), y(21), z(23) {} // default value
};
Vector3* hvector = new Vector3();
Memory view of hvector

Address of hvalue: 0x00007fa9b6e04080
Address of harray: 0x00007fa9b6f04080
Address of hvector: 0x00007fa9b6f040a0

Deallocates memory

If the memory remains allocated after use, it will cause a memory leak. To avoid that, we need to free the memory(a.k.a. delete the pointer) using “delete”.

delete hvalue;
delete harray;
delete hvector;

⚠️ Using freed pointer
As soon as the memory is freed, this pointer could not be used anymore, otherwise, it leads to ERROR. To avoid this, we can assign 0 or std::nullptr to the freed pointer.

delete hvalue;
hvalue = 0;
// later use
if(hvalue != 0) {
std::cout << *hvalue << std::endl;
}

⚠️ Freeing the same pointer multiple time
This can create hard-to-find bugs, try to avoid them!

--

--