SyntaxPilot
Courses/C Coding Questions/Lesson 21
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C Coding Questions · Lesson 21 of 30

Pointer questions II

dynamic array with malloc and reallocreturn an array from a function (the dangling pointer bug)free and memory leaks

These are the notes for C Coding Questions, episode 21, placement practice for people who finished the SyntaxPilot C course. Pointer questions, part two, about memory you manage yourself: a dynamic array that grows with malloc and realloc, returning an array from a function (the dangling pointer bug), and finding and fixing a memory leak (plus double free).

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc, Linux x86-64: 4-byte int, 8-byte pointers, an 8 MB stack), the SyntaxPilot compiler's C command with warnings on, and every output below is real, with standard output going to a pipe as in the SyntaxPilot compiler. In the input lines below, ⏎ means pressing Enter.

Real-life pictures

In real life In C
a school bag: small, emptied for you every day the stack: local variables, a few MB, gone when the function returns
a rented godown: huge, but you ask for it and return it yourself the heap: memory from malloc, returned with free
moving to a bigger flat and carrying everything over realloc: a bigger block, the old data copied
directions to a wedding tent that's packed up the next day a dangling pointer: the address of memory that's gone
a hotel guest who never checks out a memory leak: malloc without free

The idea: stack and heap

  • The stack holds each function's local variables. It is fast and automatic: a function's locals appear when it's called and vanish when it returns. It is also small (8 MB by default on Linux).
  • The heap is a large pool of memory you manage yourself:
  • malloc(bytes) (from <stdlib.h>) reserves a block of bytes bytes and returns its address, or NULL (a pointer to nothing) if it can't. The block's contents start as garbage.
  • realloc(p, bytes) resizes a block: it may grow it where it is, or get a new block, copy the old contents, free the old one, and return the new address. NULL if it fails (and then the old block is still yours).
  • free(p) gives a block back. Every malloc needs exactly one free. free(NULL) does nothing.
  • malloc(n * sizeof(int)) means "room for n ints"; sizeof gives a type's size in bytes.

Q1: Store numbers when you don't know how many

Problem. Read integers until the input ends (the count is not given). Print the count, the sum, and the numbers in reverse (so all of them must be kept).

Think out loud.

  • 4 8 15 16 23 42 7 9 → count = 8, sum = 124, reversed 9 7 42 23 16 15 8 4.
  • Edge cases: no numbers at all; a million numbers; memory running out.
  • The sum of many ints can pass 2,147,483,647, so it's a long long.

The obvious attempt: a fixed array

#include <stdio.h>

int main() {
    int a[5], n = 0, x;
    while (n < 5 && scanf("%d", &x) == 1)
        a[n++] = x;
    long long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    printf("count = %d, sum = %lld\nreversed:", n, sum);
    for (int i = n - 1; i >= 0; i--) printf(" %d", a[i]);
    printf("\n");
    return 0;
}

Input 4 8 15 16 23 42 7 9⏎:

Output:

count = 5, sum = 66
reversed: 23 16 15 8 4

The n < 5 check stops us writing past the end (without it, the sixth number would be written outside the array: undefined behaviour), but three numbers are simply lost.

The obvious fix: make it huge

#include <stdio.h>

int main() {
    int a[10000000], n = 0, x;
    while (n < 10000000 && scanf("%d", &x) == 1)
        a[n++] = x;
    long long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    printf("count = %d, sum = %lld\nreversed:", n, sum);
    for (int i = n - 1; i >= 0; i--) printf(" %d", a[i]);
    printf("\n");
    return 0;
}

Input 4 8 15 16 23 42 7 9⏎:

Output:

Segmentation fault

Why. 10,000,000 ints × 4 bytes = 40 MB, but a local array lives on the stack, and the stack is 8 MB. Asking for more is a stack overflow: the program crashes as soon as it touches the array, before reading anything. (A static or global array of that size would live elsewhere and work, but it still wastes 40 MB for 8 numbers and still has a fixed limit.)

The fix: a dynamic array on the heap

Keep a capacity cap (how many ints fit now) and a count n (how many we have). Start small; when n == cap, double cap and realloc.

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

int main() {
    int cap = 2, n = 0, x;
    int *a = malloc(cap * sizeof(int));
    if (a == NULL) return 1;
    while (scanf("%d", &x) == 1) {
        if (n == cap) {
            cap *= 2;
            int *bigger = realloc(a, cap * sizeof(int));
            if (bigger == NULL) { free(a); return 1; }
            a = bigger;
            printf("grew to %d\n", cap);
        }
        a[n++] = x;
    }
    long long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    printf("count = %d, sum = %lld\nreversed:", n, sum);
    for (int i = n - 1; i >= 0; i--) printf(" %d", a[i]);
    printf("\n");
    free(a);
    return 0;
}

Input 4 8 15 16 23 42 7 9⏎:

Output:

grew to 4
grew to 8
count = 8, sum = 124
reversed: 9 7 42 23 16 15 8 4

With no input at all:

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

int main() {
    int cap = 2, n = 0, x;
    int *a = malloc(cap * sizeof(int));
    if (a == NULL) return 1;
    while (scanf("%d", &x) == 1) {
        if (n == cap) {
            cap *= 2;
            int *bigger = realloc(a, cap * sizeof(int));
            if (bigger == NULL) { free(a); return 1; }
            a = bigger;
            printf("grew to %d\n", cap);
        }
        a[n++] = x;
    }
    long long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    printf("count = %d, sum = %lld\nreversed:", n, sum);
    for (int i = n - 1; i >= 0; i--) printf(" %d", a[i]);
    printf("\n");
    free(a);
    return 0;
}

Output:

count = 0, sum = 0
reversed:

On the numbers 1 to 1,000,000 (input seq 1 1000000), it grew 19 times (4, 8, … 1,048,576) and printed count = 1000000, sum = 500000500000.

Why bigger? If realloc fails it returns NULL but the old block is still allocated. a = realloc(a, ...) would overwrite our only copy of its address with NULL, and the old block could never be freed: a leak (and the numbers are lost). Keep the result in a new pointer, check it, then assign.

Complexity: why doubling is fast. A realloc may copy everything so far. With doubling, the copies are 2 + 4 + 8 + … + n < 2n in total, so reading n numbers is O(n), and each new number costs O(1) on average. Some steps are expensive, but averaged over all of them the cost is constant: this is called amortised O(1). Growing by one slot each time would copy 1 + 2 + … + n = O(n²). Space: O(n), at most about twice what's needed. (C++'s std::vector and Python's list grow the same way.)

Q2: Return an array from a function

Problem. Write make_squares(n) that returns an array holding 1, 4, 9, …, n². A C function can't return a whole array, so it returns a pointer to its first element.

Think out loud. make_squares(5) → 1 4 9 16 25. Edge cases: who owns the memory afterwards? n = 0? malloc failing?

The obvious attempt: return a local array

#include <stdio.h>

int *make_squares(int n) {
    int a[10];
    for (int i = 0; i < n; i++)
        a[i] = (i + 1) * (i + 1);
    return a;
}

int main() {
    int *sq = make_squares(5);
    for (int i = 0; i < 5; i++)
        printf("%d ", sq[i]);
    printf("\n");
    return 0;
}

Compiler output:

main.c: In function ‘make_squares’:
main.c:7:12: warning: function returns address of local variable [-Wreturn-local-addr]
    7 |     return a;
      |            ^

Output:

Segmentation fault

Why. a is a local: it lives in make_squares' part of the stack, which is reused the moment the function returns. The returned address points to memory that is no longer ours: a dangling pointer. Using it is undefined behaviour. gcc saw this, warned, and (at -O2) deliberately returned a null pointer, so reading sq[0] crashed at once. Another compiler, or -O0, may print the right numbers by luck and break later, when another call reuses that stack memory. Never rely on it.

Fix one: malloc inside, the caller frees

Heap memory stays until someone frees it, so returning its address is fine. The function's contract is now: the caller owns the result and must free it.

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

int *make_squares(int n) {
    int *a = malloc(n * sizeof(int));
    if (a == NULL) return NULL;
    for (int i = 0; i < n; i++)
        a[i] = (i + 1) * (i + 1);
    return a;
}

int main() {
    int *sq = make_squares(5);
    if (sq == NULL) return 1;
    for (int i = 0; i < 5; i++)
        printf("%d ", sq[i]);
    printf("\n");
    free(sq);
    return 0;
}

Output:

1 4 9 16 25 

(malloc(0) may return NULL or a unique pointer; both are allowed to be passed to free. If n can be 0, a careful caller treats NULL as "empty" only when n is 0.)

Fix two: the caller passes the buffer

No heap at all: the caller owns an array, and the function fills it. This is how fgets, strcpy and snprintf work.

#include <stdio.h>

void make_squares(int *out, int n) {
    for (int i = 0; i < n; i++)
        out[i] = (i + 1) * (i + 1);
}

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

Output:

1 4 9 16 25 

A third way you'll hear: static int a[10]; inside the function. A static local lives for the whole program, so its address stays valid, but every call shares the same array: a second call overwrites the first result. Avoid it for this.

Complexity: O(n) time to fill; O(n) space (on the heap until free, or in the caller's array).

Q3: Find the leak (and the double free)

Problem. A program calls make_squares(1000) 50,000 times and adds up the last square of each. The answer is right, but a long-running version slowly fills memory and dies. Find the bug and fix it.

How to measure it. On Linux, the file /proc/self/statm holds a program's memory use in pages (fixed-size chunks of memory, 4096 bytes here); its second number is the pages in use right now. sysconf(_SC_PAGESIZE) (from <unistd.h>) gives the page size.

The obvious attempt: never free

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

long memory_mb(void) {   /* memory in use now (Linux) */
    long size, pages = 0;
    FILE *f = fopen("/proc/self/statm", "r");
    if (f == NULL) return -1;
    if (fscanf(f, "%ld %ld", &size, &pages) != 2) pages = 0;
    fclose(f);
    return pages * sysconf(_SC_PAGESIZE) / (1024 * 1024);
}

int *make_squares(int n) {
    int *a = malloc(n * sizeof(int));
    if (a == NULL) exit(1);
    for (int i = 0; i < n; i++)
        a[i] = (i + 1) * (i + 1);
    return a;
}

int main() {
    long long total = 0;
    for (int round = 1; round <= 50000; round++) {
        int *sq = make_squares(1000);
        total += sq[999];
        if (round % 10000 == 0)
            printf("round %5d: %4ld MB\n", round, memory_mb());
    }
    printf("total = %lld\n", total);
    return 0;
}

Output:

round 10000:   39 MB
round 20000:   78 MB
round 30000:  116 MB
round 40000:  154 MB
round 50000:  193 MB
total = 50000000000

Why. Each round mallocs 1000 × 4 = 4,000 bytes and never frees them: about 40 MB per 10,000 rounds. And the next round overwrites sq, so the old block's address is gone: nothing can ever free it. A memory leak is heap memory that is still allocated but that no pointer remembers. The program "works" until the machine runs out of memory.

The fix: one free per malloc

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

long memory_mb(void) {   /* memory in use now (Linux) */
    long size, pages = 0;
    FILE *f = fopen("/proc/self/statm", "r");
    if (f == NULL) return -1;
    if (fscanf(f, "%ld %ld", &size, &pages) != 2) pages = 0;
    fclose(f);
    return pages * sysconf(_SC_PAGESIZE) / (1024 * 1024);
}

int *make_squares(int n) {
    int *a = malloc(n * sizeof(int));
    if (a == NULL) exit(1);
    for (int i = 0; i < n; i++)
        a[i] = (i + 1) * (i + 1);
    return a;
}

int main() {
    long long total = 0;
    for (int round = 1; round <= 50000; round++) {
        int *sq = make_squares(1000);
        total += sq[999];
        free(sq);
        if (round % 10000 == 0)
            printf("round %5d: %4ld MB\n", round, memory_mb());
    }
    printf("total = %lld\n", total);
    return 0;
}

Output:

round 10000:    1 MB
round 20000:    1 MB
round 30000:    1 MB
round 40000:    1 MB
round 50000:    1 MB
total = 50000000000

Flat: each round reuses the block the previous round gave back. Complexity: O(rounds × n) time either way; memory O(n) at any moment instead of growing with every round. Tools like Valgrind (valgrind --leak-check=full ./main) and gcc's -fsanitize=address find leaks automatically on your own machine.

The opposite mistake: freeing twice

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

int main() {
    int *a = malloc(3 * sizeof(int));
    if (a == NULL) return 1;
    a[0] = 7; a[1] = 8; a[2] = 9;
    printf("a[1] = %d\n", a[1]);
    free(a);
    printf("freed once\n");
    free(a);
    printf("freed twice\n");
    return 0;
}

Compiler output:

main.c: In function ‘main’:
main.c:11:5: warning: pointer ‘a’ used after ‘free’ [-Wuse-after-free]
   11 |     free(a);
      |     ^~~~~~~
main.c:9:5: note: call to ‘free’ here
    9 |     free(a);
      |     ^~~~~~~

Output:

free(): double free detected in tcache 2
Aborted

gcc warns (-Wuse-after-free), and glibc's memory manager catches the second free and aborts the program. A double free (freeing the same block twice) and a use after free (reading or writing a block after freeing it) are undefined behaviour; this time the library caught it, but often such bugs corrupt memory silently. Notice that even a[1] = 8 and freed once are missing: with output going to a pipe, printf keeps text in a buffer and writes it out later, and an aborted program never writes its buffer.

The habit: right after free(p), write p = NULL;. A second free(NULL) does nothing, and an accidental *p now crashes loudly instead of quietly using freed memory.

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

int main() {
    int *a = malloc(3 * sizeof(int));
    if (a == NULL) return 1;
    a[0] = 7; a[1] = 8; a[2] = 9;
    printf("a[1] = %d\n", a[1]);
    free(a);
    a = NULL;
    printf("freed once\n");
    free(a);
    printf("freed twice\n");
    return 0;
}

Output:

a[1] = 8
freed once
freed twice

Complexity summary

Task Method Time Space
store n numbers, n unknown int a[5] O(n), loses numbers O(1)
int a[10000000] local crashes (stack overflow) 40 MB
heap, realloc +1 each time O(n²) copies O(n)
heap, double the capacity O(n), amortised O(1) per number O(n), ≤ about 2n
return an array local array dangling pointer (UB)
malloc inside, caller frees O(n) O(n) heap
caller passes the buffer O(n) O(n), caller's
loop of mallocs no free O(rounds × n) grows with rounds
free each round O(rounds × n) O(n)

Common mistakes (and the real results)

Mistake What you see Why Fix
int a[10000000]; local Segmentation fault stack overflow (8 MB stack) malloc on the heap
no NULL check after malloc a crash when memory runs out malloc returned NULL if (a == NULL) ...
a = realloc(a, ...) no error; a leak if it fails NULL overwrites the only address int *bigger = realloc(a, ...)
malloc(n) for n ints writes past the block (UB) that's n bytes malloc(n * sizeof(int))
return a local array warning: function returns address of local variable [-Wreturn-local-addr], Segmentation fault dangling pointer (UB) malloc and the caller frees, or pass a buffer
malloc in a loop, no free no error: memory grows to ~190 MB memory leak free(sq) each round
free(a); free(a); warning: pointer 'a' used after 'free' [-Wuse-after-free], free(): double free detected in tcache 2, Aborted double free (UB) free(a); a = NULL;
using a[0] after free(a) anything (UB) use after free don't; set it to NULL
free of a non-heap pointer crash (UB) only malloc/realloc results may be freed free only what you allocated

Your turn: read a line of any length (solution)

Problem. Read one whole line, however long, into a string you allocate yourself, and print its length. hello world → 11; an empty line → 0.

Idea. getchar() returns the next character, or EOF at the end of input. Grow a char buffer exactly like Q1: start small, double with realloc when full, always leaving room for the '\0' that ends a C string. Stop at '\n' or EOF. O(n) time and space.

Show the solution
#include <stdio.h>
#include <stdlib.h>

char *read_line(void) {
    int cap = 4, n = 0, c;
    char *s = malloc(cap);
    if (s == NULL) return NULL;
    while ((c = getchar()) != EOF && c != '\n') {
        if (n + 1 == cap) {              /* keep room for '\0' */
            cap *= 2;
            char *bigger = realloc(s, cap);
            if (bigger == NULL) { free(s); return NULL; }
            s = bigger;
        }
        s[n++] = (char)c;
    }
    if (c == EOF && n == 0) { free(s); return NULL; }   /* no more lines */
    s[n] = '\0';
    return s;
}

int main() {
    char *line;
    while ((line = read_line()) != NULL) {
        int len = 0;
        while (line[len] != '\0') len++;
        printf("[%s] length %d\n", line, len);
        free(line);
    }
    return 0;
}

Input hello world⏎ ⏎ the quick brown fox jumps over the lazy dog⏎:

Output:

[hello world] length 11
[] length 0
[the quick brown fox jumps over the lazy dog] length 43

c is an int, not a char, so it can hold EOF (−1) as well as every character. POSIX systems also offer getline(), which does exactly this for you.

Practice questions (with solutions)

1. A 2D grid of r × c ints with one malloc. Allocate a grid whose size is read at run time.

Solution

One block of r * c ints, and element (i, j) at index i * c + j (row-major order, as in episode 19). One malloc, one free.

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

int main() {
    int r = 3, c = 4;
    int *g = malloc((size_t)r * c * sizeof(int));
    if (g == NULL) return 1;
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            g[i * c + j] = i * 10 + j;
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) printf("%4d", g[i * c + j]);
        printf("\n");
    }
    free(g);
    return 0;
}

Output:

   0   1   2   3
  10  11  12  13
  20  21  22  23

2. append(&arr, &n, &cap, x). Package Q1's growth into a function.

Solution

The function must change the caller's pointer, count and capacity, so it takes their addresses (episode 20). It returns 0 if memory runs out.

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

int append(int **arr, int *n, int *cap, int x) {
    if (*n == *cap) {
        int new_cap = *cap ? *cap * 2 : 2;
        int *bigger = realloc(*arr, new_cap * sizeof(int));
        if (bigger == NULL) return 0;
        *arr = bigger;
        *cap = new_cap;
    }
    (*arr)[(*n)++] = x;
    return 1;
}

int main() {
    int *a = NULL, n = 0, cap = 0;
    for (int x = 1; x <= 10; x++)
        if (!append(&a, &n, &cap, x * x)) { free(a); return 1; }
    printf("n = %d, cap = %d:", n, cap);
    for (int i = 0; i < n; i++) printf(" %d", a[i]);
    printf("\n");
    free(a);
    return 0;
}

Output:

n = 10, cap = 16: 1 4 9 16 25 36 49 64 81 100

realloc(NULL, size) behaves like malloc(size), so the array can start as NULL.

3. Find the leak: a string duplicated in a loop.

for (int i = 0; i < 3; i++) {
    char *copy = malloc(strlen(word) + 1);
    strcpy(copy, word);
    printf("%s\n", copy);
}
Solution

Each round mallocs a copy and never frees it: 3 leaked blocks. Free it after use. (+ 1 is for the '\0'.)

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

int main() {
    const char *word = "SyntaxPilot";
    for (int i = 0; i < 3; i++) {
        char *copy = malloc(strlen(word) + 1);
        if (copy == NULL) return 1;
        strcpy(copy, word);
        printf("%s\n", copy);
        free(copy);
    }
    return 0;
}

Output:

SyntaxPilot
SyntaxPilot
SyntaxPilot

Quick quiz

#include <stdlib.h>

int main() {
    char *p = malloc(6);
    char *q = malloc(6);
    p = q;
    free(p);
    return 0;
}

How many blocks are leaked? (A) 0 (B) 1 (C) 2 (D) It's a double free

Answer

(B) 1. p = q throws away the only copy of the first block's address, so it can never be freed. free(p) frees the second block exactly once, so it is not a double free. (Freeing q as well would be.) It compiles and runs with no message: leaks are silent.

Interview questions

  1. Stack vs heap? Stack: locals, automatic, small, freed on return. Heap: malloc/free, large, lives until freed.
  2. What does malloc return on failure? NULL; always check it.
  3. What does realloc do, and why not p = realloc(p, n)? Resizes (may move and copy); on failure it returns NULL and the old block stays, so the direct assignment leaks it.
  4. Why double the capacity rather than add a fixed amount? Total copying stays O(n), so appends are amortised O(1); adding a constant gives O(n²).
  5. Why is returning a local array wrong? Its storage ends when the function returns: a dangling pointer.
  6. Three ways to return an array from a function? malloc (caller frees), a caller-provided buffer, or a static array (shared between calls).
  7. What is a memory leak? How do you find one? Allocated memory no pointer refers to; Valgrind, AddressSanitizer, or watching memory grow.
  8. What happens on a double free? Undefined behaviour; glibc often detects it and aborts.
  9. Why set a pointer to NULL after free? A second free is harmless, and accidental use fails loudly.
  10. malloc vs calloc? calloc(n, size) also zeroes the memory (and checks n * size for overflow).

Glossary

Term Meaning Example
Stack Memory for function locals, automatic and small int a[5]; in main
Stack overflow Using more stack than there is: a crash int a[10000000]; local
Heap Memory you request and return yourself malloc / free
malloc(bytes) Reserve a heap block; its address, or NULL malloc(n * sizeof(int))
NULL A pointer to nothing if (a == NULL)
sizeof The size of a type in bytes sizeof(int) = 4
realloc(p, bytes) Resize a block, maybe moving and copying it realloc(a, cap * sizeof(int))
free(p) Give a heap block back free(a);
Dynamic array An array on the heap that grows as needed Q1's a, n, cap
Capacity How many elements fit before growing cap
Amortised O(1) Constant cost on average over many operations append with doubling
Dangling pointer A pointer to memory that is no longer valid returning a local array
-Wreturn-local-addr gcc warning for returning a local's address return a;
Ownership Who is responsible for freeing a block "the caller must free it"
Memory leak Allocated memory that nothing points to any more malloc in a loop, no free
Page A fixed-size chunk of memory the OS manages (4096 bytes here) /proc/self/statm counts pages
Double free Freeing the same block twice (UB) free(a); free(a);
Use after free Using a block after freeing it (UB) a[0] after free(a)
-Wuse-after-free gcc warning for using a pointer after free the second free(a)
Abort The program stopped on purpose by the library Aborted
Output buffer Text printf holds before writing it out lost when a program aborts
getchar() / EOF Read one character; EOF at the end of input while ((c = getchar()) != EOF)
static local A local that lives for the whole program static int a[10];
Valgrind / AddressSanitizer Tools that detect leaks and bad memory use -fsanitize=address
Undefined behaviour (UB) The C standard makes no promise about the result dangling pointer use

Summary

  • Locals live on the small, automatic stack; a huge local array overflows it. Big or variable-size data goes on the heap: malloc, check for NULL, free.
  • A dynamic array keeps n and cap and doubles with realloc when full: O(n) to read n numbers, amortised O(1) per number. Keep realloc's result in a new pointer first.
  • Never return a local array: it's a dangling pointer. Return malloc-ed memory (the caller frees it) or fill a buffer the caller passes.
  • One free per malloc. A lost address is a memory leak; a second free is a double free. Set pointers to NULL after freeing.

Next episode: Recursion questions I: factorial and sum of digits with recursion, fast power x^n (divide and conquer), base case and stack depth.