Static vs. Dynamic Allocation

Learn the differences between stack and heap allocations.

Introduction

We know how to allocate variables on the heap. Now, let’s look at the differences between stack and heap allocations.

Management

Let’s compare the stack and the heap from a memory management point of view.

Stack

The stack is managed automatically by the compiler. A function cleans its stack when it ends. Cleaning the stack means restoring it back to the state it was before the function call. The compiler does it by popping the stack.

The consequence is that memory leaks are not possible with stack allocations, the code needed to free the memory is always generated by the compiler.

Heap

It’s the programmer’s responsibility to manage heap allocations. The usual process of working with the stack is as follows:

  1. Dynamically allocate memory using malloc or calloc.
  2. Use the memory.
  3. When the memory is no longer needed, we must free it manually by calling free.

The memory doesn’t get automatically deallocated like in the stack case. If we don’t call the function free, the memory will remain allocated and owned by our program. The operating system automatically reclaims the memory when the program stops running.

We call allocated and not freed memory a leak. The leaks can pile up. If the program leaks huge amounts of memory, and if it runs for a long period of time, the system may run out of memory, causing a serious failure. The reason for this behavior is that the operating system reclaims the memory only once the program stops.

Consider the following two functions, called leak (line 4) and noleak (line 16).

  • leak dynamically allocates memory using malloc but never frees it.
  • noleak dynamically allocates memory using malloc but frees it at the end of the function (line 27).

Get hands-on with 1200+ tech skills courses.