Skip to content

Memory bugs

Read · 1 of 4

C trusts you completely

Out of bounds: a[n] is one past the end. C won't stop you, it reads or overwrites whatever lives there, and the program misbehaves somewhere else later.

Leak: memory you malloc and never free. Harmless in a tiny program, fatal in a server running for days.

Use after free / dangling pointer: after free(p), the memory may be handed to someone else. Set p = NULL; so a mistake crashes loudly instead of silently corrupting data.

Habit: every loop over an array uses i < n, and every malloc has its free written straight away.

Read this lesson as text

Off-by-one, leaks, and using memory after free: the bugs C won't warn you about.

C trusts you completely

Out of bounds: a[n] is one past the end. C won't stop you, it reads or overwrites whatever lives there, and the program misbehaves somewhere else later.

Leak: memory you malloc and never free. Harmless in a tiny program, fatal in a server running for days.

Use after free / dangling pointer: after free(p), the memory may be handed to someone else. Set p = NULL; so a mistake crashes loudly instead of silently corrupting data.

Habit: every loop over an array uses i < n, and every malloc has its free written straight away.

Count the turns

#include <stdio.h>

int main() {
    int count = 0;
    for (int i = 0; i <= 5; i++) count++;
    printf("%d\n", count);
    return 0;
}

An array has 5 elements. This loop is meant to visit each once. How many turns does it take?

  • 6
  • 5
  • 4
Show the answer

6 i takes 0, 1, 2, 3, 4 and 5: six turns. With a 5-element array, the last one touches a[5], past the end. Use i < 5.

Break it: Break the total

This should print the sum of n numbers. Find an input where the answer is wrong.

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

int main() {
    int n, total = 0;
    scanf("%d", &n);
    int *a = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    for (int i = 1; i < n; i++) total += a[i];
    printf("%d\n", total);
    free(a);
    return 0;
}

Input rules: first line n (1 to 20), second line n whole numbers between -1000 and 1000.

Exercise: Fix the copy

copyOf should return a new malloc'd copy of the array, so changing the original afterwards doesn't affect it. It prints the wrong thing. Fix copyOf.