The Heap

Learn about heap memory that's available for use when a C program is run.

We'll cover the following

What’s a heap?

The heap is a region of your computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger).

The stack and heap sizes are initially set (typically by the operating system) when the program runs. Unlike the fixed-size stack, there are no restrictions on the size of memory that can be allocated on a heap (apart from the obvious physical limitations of your computer). More heap memory can be available to the program by the operating system while the program is running. Also, unlike the stack, the memory allocated on the heap can be accessed by any function, anywhere in your program.

However, heap memory is slightly slower to read from and written to, because one has to use pointers to access memory on the heap. We’ll talk about pointers shortly.

Memory leak

To allocate memory on the heap, we must use the functions malloc or calloc, which are built-in C functions. Once we’ve allocated memory on the heap, we’re responsible for using the function free to deallocate that memory when we don’t need it any more. If we fail to do this, our program will have what’s known as a memory leak. That is, memory on the heap will not be freed and won’t be available to other processes.

As we’ll see in the debugging section, there’s a tool called valgrind that helps detect memory leaks.

So the stack and the heap have their own benefits and dangers in terms of memory allocation. With the theory out of the way, let’s take a look at how the stack and heap work in code.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy