C++ / a working model

118 / 163   ·   C11   ·   8 min

Interlude: Memory API

Keep this sentence

C programs rely on automatic stack allocation together with explicit heap requests to control data lifetime. Mastering the pairing of malloc and free plus typical misuse patterns is essential for robust software.

In this lesson
  1. Two Kinds of Program Memory
  2. Calling malloc Correctly
  3. Freeing Memory and Typical Pitfalls
  4. Example
  5. Exercise

Official chapter PDF

Two Kinds of Program Memory

Variables declared inside a function receive space reserved automatically by the compiler on the call stack; that space vanishes the moment the function returns. Data that must outlive the allocating call has to reside on the heap, where the programmer both requests and later returns the storage.

Calling malloc Correctly

Pass malloc the exact byte count, normally obtained by applying sizeof to a type. Cast the returned void pointer to the needed type. Always test for NULL. When copying a string add one extra byte for the terminator.

Freeing Memory and Typical Pitfalls

Every successful malloc must later be matched by free on the identical pointer. Omitting the allocation entirely, requesting one byte too few, or freeing twice commonly produce crashes or security holes. Many newer languages hide this work behind garbage collection.

Pitfalls

  • Passing an uninitialized pointer as the destination of strcpy
  • Requesting exactly strlen bytes then writing the terminator as well
  • Never calling free after a heap block is finished

Run an example

Minimum C11 · complete program · Download .c

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

int main(void) {
    int stack_val = 42;
    printf("Allocated on stack: %d\n", stack_val);
    int *heap_val = (int *)malloc(sizeof(int));
    if (heap_val == NULL) {
        printf("Heap allocation failed\n");
        return 1;
    }
    *heap_val = 99;
    printf("Allocated on heap: %d\n", *heap_val);
    const char *original = "OSTEP";
    char *copy = (char *)malloc(strlen(original) + 1);
    if (copy == NULL) {
        free(heap_val);
        printf("String allocation failed\n");
        return 1;
    }
    strcpy(copy, original);
    printf("String copy: %s\n", copy);
    free(copy);
    free(heap_val);
    printf("All heap memory released\n");
    return 0;
}

Compile locally

gcc -std=c11 -Wall -Wextra -Wpedantic -Werror ostep-14-memory-api.c -o example && ./example

Expected result

Allocated on stack: 42
Allocated on heap: 99
String copy: OSTEP
All heap memory released

CHECK YOUR UNDERSTANDING

Close the answer. Explain it.

Why does sizeof applied to a pointer obtained from malloc report only the pointer width?

Show a reference answer

sizeof is a compile-time operator that sees only the static type of the variable, never the actual number of bytes obtained at run time.

Check the sources

Drafts and official chapters change. The version mark is only the example’s minimum.

Back to the catalog