...

/

Stack vs Heap

Stack vs Heap

Keep in mind the pros and cons of allocation on stack versus heaps in order to make the right choices when creating variables.

We can choose to allocate space for a variable explicitly on the heap instead of the stack depending on our needs. To write effective code, the pros and cons for each type of allocation should be kept in mind.

Pros and cons

Stack

Heap

Fast access

Relatively slower access

Variables can only be accessed locally

Variables can be accessed from anywhere

Limit imposed on stack size (OS-dependent)

No limit imposed on heap size, as long as memory is physically available

Space allocated for variables cannot be resized

Allocated space can be resized using realloc

Variables don’t have to be explicitly deallocated

We manage the memory ourselves and are in charge of allocating and freeing variables

Space is managed efficiently by CPU (memory will not become fragmented )

No guaranteed efficient use of space (memory may become fragmented over time as blocks of memory are allocated, then freed)

...