C · Course navigation

C dynamic memory and ownership

Allocate, check, use, and free a heap buffer.

On this page
Before you start

Pointers, sizeof, and arrays.

  • Allocate, check, use, and free a heap buffer.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

malloc requests a block of uninitialized memory and returns NULL if it fails. Use sizeof *pointer to size elements consistently with the pointer type.

Every successful allocation in this example has one matching free. After free, the allocation must not be read or written. Setting the local pointer to NULL helps avoid accidental reuse through that variable.

Code example

C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *values = malloc(3 * sizeof *values);
    if (values == NULL) return 1;
    for (int i = 0; i < 3; i++) values[i] = (i + 1) * 10;
    printf("%d\n", values[2]);
    free(values);
    values = NULL;
    return 0;
}
Output
30

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2#include <stdlib.h>
3int main(void) {
4 int *values = malloc(3 * sizeof *values);
5 if (values == NULL) return 1;
6 for (int i = 0; i < 3; i++) values[i] = (i + 1) * 10;
7 printf("%d\n", values[2]);
8 free(values);
9 values = NULL;
10 return 0;
11}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Request space for three ints; the walkthrough assumes successful allocation.values -> allocated block
—
Stop with failure status if allocation failed.values -> allocated block
—
Initialize all three elements before reading.values = [10, 20, 30]
—
Read the third in-bounds element.values = [10, 20, 30]
30
Release the allocation.allocation no longer valid
30
Clear this pointer variable.values = NULL
30

Behind the scenes

How C processes this code

The C compiler produces a native program. Variables occupy memory, and execution enters main.

Cost and common mistakes

O(n) initialization time and O(n) allocated storage for n elements; allocation cost depends on the allocator.

  • Do not double-free or use memory after free.
  • For a variable allocation size, check multiplication overflow before computing bytes.

Try it yourself

Allocate five ints and print the fifth initialized value.

Reveal answer and reasoning

Change both the allocation count and loop bound to 5, then print values[4], which is 50.

Further reading