Heap Memory
What is Heap?
Heap is a memory region allotted to every program. Unlike stack, heap memory can be dynamically allocated. This means that the program can 'request' and 'release' memory from the heap segment whenever it requires. Also, this memory is global, i.e. it can be accessed and modified from anywhere within a program and is not localized to the function where it is allocated. This is accomplished using 'pointers' to reference dynamically allocated memory which in turn leads to a small degradation in performance as compared to using local variables (on the stack).
Using dynamic memory
stdlib.h
provides with standard library functions to access, modify and manage dynamic memory. Commonly used functions include malloc and free:
The documentation about 'malloc' and 'free' says:
malloc:
free:
It is important to note that these memory allocation functions are provided by the standard library. These functions provide a layer between the developer and the operating system that efficiently manages heap memory. It is the responsibility of the developer to 'free' any allocated memory after using it exactly once. Internally, these functions use two system calls sbrk and mmap to request and release heap memory from the operating system. This post discusses these system calls in detail.
Last updated