Heap and Stack Memory .

Stack:

Static in memory and allocation happens only during compile time. It’s a special region of your computer’s memory that stores temporary variables created by each function main(). The stack is a “LIFO”(last in, first out) data structure. When a function is called, all local instances will be push on to the current stack and pop/freed when the function has returned. Once a stack variable is freed, that region of memory becomes available for other stack variables.

  • the stack grows and shrinks as functions push and pop local variables
  • There is no need to manage the memory yourself, variables are allocated and freed automatically, space is managed efficiently by CPU.
  • the stack has size limits, cannot be resized.
  • stack variables only exist while the function that created them, is running. 
  • very fast access

Heap:

The heap is a region of your computer’s memory that is not managed automatically for you and not as by the CPU. Dynamic in memory and allocation happens during runtime. Values can be referenced at any time through a memory address. To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions and use free() to deallocate that memory(garbage collector in java). if not, the program will have “memory leak”

  • variables can be accessed globally.
  • no limit on memory size.
  • slower access.
  • no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed.
  • you must manage memory.
  • variables can be resized using realloc().

However in Swift, we don’t have to use free() to deallocate the memory in Swift because we have an ARC.

What is an ARC(Automatic Reference Counting)?

ARC (Automatic Reference Counting) to track and manage your app’s memory usage. ARC automatically frees up the memory used by class instances when those instances are no longer needed.