In: Computer Science
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).
To allocate memory on the heap, you must use malloc()
or calloc()
, which are built-in C functions. Once you
have allocated memory on the heap, you are responsible for using
free()
to deallocate that memory once you don't need
it any more. If you fail to do this, your program will have what is
known as a memory leak. That is, memory on the
heap will still be set aside (and won't be available to other
processes). As we will see in the debugging section, there is a
tool called valgrind
that can help you detect memory
leaks.
Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.
Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
When should you use the heap, and when should you use the stack?
If you need to allocate a large block of memory (e.g. a large
array, or a big struct), and you need to keep that variable around
a long time (like a global), then you should allocate it on the
heap. If you are dealing with relatively small variables that only
need to persist as long as the function using them is alive, then
you should use the stack, it's easier and faster. If you need
variables like arrays and structs that can change size dynamically
(e.g. arrays that can grow or shrink as needed) then you will
likely need to allocate them on the heap, and use dynamic memory
allocation functions like malloc()
,
calloc()
, realloc()
and
free()
to manage that memory "by hand". We will talk
about dynamically allocated data structures after we talk about
pointers.
ge memory (you're in charge of allocating and freeing variables)
realloc()