The Heap
The heap is a place in memory which a program can use to dynamically create objects. Creating objects on the heap has some advantages compared to using the stack:
- Heap allocations can be dynamically sized
- Heap allocations "persist" when a function returns
There are also some disadvantages however:
- Heap allocations can be slower
- Heap allocations must be manually cleaned up
Using the heap
In C, there are a number of functions used to interact with the heap, but we're going to focus on the two core ones:
malloc
: allocaten
bytes on the heapfree
: free the given allocation
Let's see how these could be used in a program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
unsigned alloc_size = 0;
char *stuff;
printf("Number of bytes? ");
scanf("%u", &alloc_size);
stuff = malloc(alloc_size + 1);
memset(stuff, 0, alloc_size + 1);
read(0, stuff, alloc_size);
printf("You wrote: %s", stuff);
free(stuff);
return 0;
}
This program reads in a size from the user, creates an allocation of that size on the heap, reads in that many bytes, then prints it back out to the user.