0Pricing
C Academy · Lesson

malloc and free

Allocate on the heap.

The Heap

So far variables lived on the stack with a fixed lifetime. The heap lets you request memory at runtime and keep it as long as you need.

You manage heap memory yourself using <stdlib.h> functions.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(sizeof(int));
    *p = 99;
    printf("%d\n", *p);
    free(p);
    return 0;
}

Calling malloc

malloc(size) reserves size bytes and returns a pointer to them, or NULL on failure.

The memory is uninitialized: its contents are indeterminate.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(sizeof(int));
    *p = 7;
    printf("value = %d\n", *p);
    free(p);
    return 0;
}

All lessons in this course

  1. malloc and free
  2. calloc and realloc
  3. Memory Leaks
  4. Dangling Pointers
← Back to C Academy