C Workshop · Dynamic Memory
Foundation C

malloc and free

Stack variables disappear when a function returns. malloc takes bytes from the heap and you must free them.

What it is

The stack is automatic: int x dies when the function returns. The heap is a warehouse you rent with malloc and must give back with free. Dynamic memory is that warehouse.

Approach

  1. malloc the right number of bytes.
  2. Check the pointer.
  3. Use *p or p[i].
  4. free(p) exactly once.

Where this is used in the real world

Diagram

1

malloc

heap box

2

*p=7

write

3

printf

7

4

free

release

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <stdlib.h>
3int main(void) {
4    int *p = malloc(sizeof(int));
5    if (!p) return 1;
6    *p = 7;
7    printf("%d\n", *p);
8    free(p);
9    return 0;
10}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. malloc(sizeof(int)) asks for:

Heap.

2. If malloc returns NULL:

Check.

3. free(p) does:

Release.

4. Using *p after free is:

Dangling.

5. calloc vs malloc:

Zero fill.