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:

There are also some disadvantages however:

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:

Let's see how these could be used in a program:

#include <stdio.h>
#include <stdlib.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(0, stuff, alloc_size + 1);

    read(0, stuff, alloc_size);

    printf("You wrote: %s", 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.