SyntaxPilot
Courses/C Programming/Lesson 14

C Programming · Lesson 14 of 30 · 11 min

Dynamic memory: malloc, calloc, realloc, free

queued

These are the notes for C episode 14. Up to now every array had a size written in the code. Today a teacher's marks program only learns the class size when it runs, so both obvious fixes crash: a small array overflows and a huge one doesn't fit on the stack. You fix it by renting memory while the program runs from the heap with malloc, then meet calloc (a zeroed block), realloc (grow a block) and free (give it back), and the classic bugs: returning a local array, memory leaks and double free. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.

The problem: how many students?

You write a marks program in April for 30 students: int marks[30];. On admission day there are 42, so 12 have no box. Next year there are 8, so 22 boxes are wasted. The real number is known only when the teacher runs the program and types it.

Here is the program with room for 5, given 8 students (input 8 70 80 90 60 75 88 92 65):

#include <stdio.h>

int main() {
    int marks[5];
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &marks[i]);
    printf("Saved %d students\n", n);
    return 0;
}

Output:

*** stack smashing detected ***: terminated

Marks 6, 7 and 8 were written past the end of the array, over memory that belonged to something else. Writing outside an array is undefined behaviour; here the C library's stack protector noticed the damage and killed the program (so suddenly that even our printf line never appeared).

The "obvious fix": make it huge.

#include <stdio.h>

int main() {
    int marks[10000000];   // ten million, just in case
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &marks[i]);
    printf("Saved %d students\n", n);
    return 0;
}

Output (same 8 students):

Segmentation fault

It crashed before reading a single mark.

Why both crashed

  • int marks[5];: an array's size is fixed when you write the code. 8 students overflow 5 boxes.
  • Local variables, arrays included, live on the stack: a small area, about 8 MB on Linux by default.
  • 10,000,000 ints × 4 bytes = 40 MB: it doesn't fit, so the operating system stops the program (Segmentation fault).
  • Idea: wait until the program knows n, then ask for exactly n boxes. Memory asked for while the program runs is called dynamic memory.

Stack vs heap

Real-life example: your study desk vs a rented godown.

In real life In C
Your study desk: small, cleared when you leave The stack: local variables, freed automatically when the function ends
A rented godown (warehouse): big, any size you ask for The heap: memory you ask for at run time with malloc
Return the key, or you keep paying rent free(p): give the memory back
Stack Heap
What lives there local variables, function parameters blocks from malloc, calloc, realloc
Size small (about 8 MB on Linux) large (limited by the machine's memory)
Size decided when you write the code while the program runs
Freed automatically, when the function returns only when you call free (or the program ends)

malloc and free

malloc (memory allocate) lives in <stdlib.h>. It takes a number of bytes and returns the address of the first byte of a new block, or NULL if there is no memory left. A pointer to a block works exactly like an array: marks[i].

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

int main() {
    int n;
    scanf("%d", &n);
    int *marks = malloc(n * sizeof(int));
    if (marks == NULL) {
        printf("Out of memory\n");
        return 1;
    }
    for (int i = 0; i < n; i++) scanf("%d", &marks[i]);
    printf("Saved %d students. Last mark: %d\n", n, marks[n - 1]);
    free(marks);
    return 0;
}

Input 8 70 80 90 60 75 88 92 65, output:

Saved 8 students. Last mark: 65
  • sizeof(int) is 4 bytes, so for 8 students malloc(8 * sizeof(int)) rents 32 bytes.
  • malloc returns void * (an address with no type); C converts it to int * automatically.
  • Always check for NULL before using the block.
  • free(marks) returns the block. After free, the pointer still holds the old address, but you must not use it.

The ten million marks that crashed the stack fit easily on the heap:

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

int main() {
    int n = 10000000;
    int *marks = malloc(n * sizeof(int));
    if (marks == NULL) return 1;
    for (int i = 0; i < n; i++) marks[i] = i % 101;
    printf("Stored %d marks, %zu MB\n", n, n * sizeof(int) / 1000000);
    free(marks);
    return 0;
}

Output:

Stored 10000000 marks, 40 MB

The malloc recipe

  1. #include <stdlib.h>
  2. Bytes = how many × sizeof(type): int *p = malloc(n * sizeof(int));
  3. if (p == NULL): no memory, stop.
  4. Use it like an array: p[i].
  5. free(p) when you're done.

calloc: a clean block

What is inside a block malloc gives you? Rent 6 ints, fill them with 7s, free them, then rent 6 ints again and print them without writing anything (input 7 7 7 7 7 7):

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

int main() {
    int *a = malloc(6 * sizeof(int));
    for (int i = 0; i < 6; i++) scanf("%d", &a[i]);
    free(a);                       // give it back

    int *b = malloc(6 * sizeof(int));
    for (int i = 0; i < 6; i++) printf("%d ", b[i]);
    printf("\n");
    free(b);
    return 0;
}

Output (the first number changes on every run):

1536207286 5 0 0 7 7

malloc does not clear memory: you get whatever the last user left there (the two 7s), plus some of malloc's own bookkeeping (the big number and the 5). Reading memory you never wrote is a bug.

calloc(count, size) (contiguous allocate) takes how many and the size of each, and fills the whole block with zeros:

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

int main() {
    int *a = malloc(6 * sizeof(int));
    for (int i = 0; i < 6; i++) scanf("%d", &a[i]);
    free(a);                       // give it back

    int *b = calloc(6, sizeof(int));
    for (int i = 0; i < 6; i++) printf("%d ", b[i]);
    printf("\n");
    free(b);
    return 0;
}

Output:

0 0 0 0 0 0

Use calloc for counters and totals that must start at zero.

realloc: grow a block

Two late admissions: a block of 3 marks must become 5, without losing the 3. realloc(p, new_size_in_bytes) resizes a block and keeps the old values (up to the smaller of the two sizes):

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

int main() {
    int n = 3;
    int *marks = malloc(n * sizeof(int));
    marks[0] = 70; marks[1] = 85; marks[2] = 90;

    int *bigger = realloc(marks, 5 * sizeof(int));
    if (bigger == NULL) { free(marks); return 1; }
    marks = bigger;
    marks[3] = 65; marks[4] = 95;
    n = 5;

    for (int i = 0; i < n; i++) printf("%d ", marks[i]);
    printf("\n");
    free(marks);
    return 0;
}

Output:

70 85 90 65 95
  • Use a temporary pointer. If realloc fails it returns NULL, but the old block is still there. marks = realloc(marks, ...) would overwrite your only copy of its address, so you could never free it.
  • realloc may move the block to a new address. After it succeeds, use only the new pointer.
  • realloc(NULL, size) works like malloc(size).

Returning memory from a function

A local array lives on the function's "desk", which is cleared when the function returns:

#include <stdio.h>

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

int main() {
    int *p = make_list(3);
    printf("%d\n", p[0]);
    return 0;
}

gcc output and result:

main.c: In function 'make_list':
main.c:6:12: warning: function returns address of local variable [-Wreturn-local-addr]
    6 |     return list;
      |            ^~~~
Segmentation fault

(int list[n], with a size from a variable, is a variable-length array, a C99 feature. It is still on the stack.)

The fix: build the list on the heap, return that address, and let the caller free it:

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

int *make_list(int n) {
    int *list = malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) list[i] = (i + 1) * 10;
    return list;
}

int main() {
    int *p = make_list(3);
    printf("%d %d %d\n", p[0], p[1], p[2]);
    free(p);
    return 0;
}

Output:

10 20 30

Rule: whoever ends up holding the pointer is responsible for calling free. Document it ("the caller must free the result").

Memory leaks and double free

A block's life: malloc (rent) → use → free (return).

  • Memory leak: no free, so the memory stays rented with nobody using it. In a short program the operating system takes everything back at exit, so you might never notice. A server that runs for weeks and leaks a little on every request slowly eats the machine's memory until it slows down or crashes.
  • Every malloc needs exactly one free. Not zero, and not two:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *marks = malloc(3 * sizeof(int));
    scanf("%d", &marks[0]);
    free(marks);
    free(marks);       // oops, again
    printf("Done\n");
    return 0;
}

Output (input 90):

free(): double free detected in tcache 2

The C library noticed the block was returned twice and stopped the program (signal SIGABRT); even Done never printed. ("tcache" is the name of a cache inside glibc's malloc.)

The habit that prevents it: set the pointer to NULL right after free. free(NULL) is allowed and does nothing:

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

int main() {
    int *marks = malloc(3 * sizeof(int));
    scanf("%d", &marks[0]);
    free(marks);
    marks = NULL;      // forget the address
    free(marks);       // free(NULL) does nothing
    printf("Done\n");
    return 0;
}

Output:

Done

Bonus: a NULL pointer can't be used by mistake later. Using memory after freeing it (a dangling pointer, "use after free") is a silent bug; with NULL it becomes an obvious crash instead.

Common mistakes (and the real messages)

Mistake What you see Why Fix
Writing past a fixed array (int marks[5], 8 students) *** stack smashing detected ***: terminated The size was fixed in the code malloc(n * sizeof(int))
int marks[10000000]; as a local Segmentation fault The stack is only about 8 MB Put it on the heap with malloc
malloc(n) for n ints No error: you write past the block (undefined behaviour) malloc counts bytes malloc(n * sizeof(int))
Not checking for NULL A crash when memory runs out malloc can fail if (p == NULL) ...
Reading a malloc block before writing it Junk values malloc doesn't clear memory Write first, or use calloc
p = realloc(p, ...) On failure, the old block leaks NULL overwrote the only address Use a temporary pointer
Returning a local array warning: function returns address of local variable [-Wreturn-local-addr], then Segmentation fault The stack frame is gone malloc inside, caller frees
Forgetting free Nothing, until memory runs out Memory leak One free per malloc
free(p); free(p); free(): double free detected in tcache 2 Already returned free(p); p = NULL;
Using p after free(p) Junk or a crash, maybe much later Dangling pointer Set p = NULL after free

Mini project: a class report with late admissions

Read the class size, rent exactly that many ints, print a report, then grow the block for late admissions and print it again.

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

void report(int *m, int n) {
    int sum = 0, top = 0;
    for (int i = 0; i < n; i++) {
        sum += m[i];
        if (m[i] > m[top]) top = i;
    }
    printf("%d students, average %.1f, topper #%d (%d)\n",
           n, (float)sum / n, top + 1, m[top]);
}

int main() {
    int n, extra;
    scanf("%d", &n);
    int *m = malloc(n * sizeof(int));
    if (m == NULL) return 1;
    for (int i = 0; i < n; i++) scanf("%d", &m[i]);
    report(m, n);
    scanf("%d", &extra);               // late admissions
    int *bigger = realloc(m, (n + extra) * sizeof(int));
    if (bigger == NULL) { free(m); return 1; }
    m = bigger;
    for (int i = n; i < n + extra; i++) scanf("%d", &m[i]);
    n += extra;
    report(m, n);
    free(m);
    return 0;
}

Input:

4
70 85 90 60
2
95 75

Output:

4 students, average 76.2, topper #3 (90)
6 students, average 79.2, topper #5 (95)

There is no fixed size anywhere: the program rents what it needs, grows when the class grows, and returns the key at the end. Try it: also print the lowest mark.

Practice

  1. Read n prices into a malloc block and print the total.
  2. Use calloc to count how many students got each grade A to E.
  3. Keep reading marks until -1, growing the block with realloc (double its capacity when it's full).
  4. Find and fix the leak: malloc inside a loop with no free.
Solutions

Tasks 1 to 3 in one program (verified):

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

int main() {
    // 1. total of n prices
    int n;
    scanf("%d", &n);
    float *price = malloc(n * sizeof(float));
    if (price == NULL) return 1;
    float total = 0;
    for (int i = 0; i < n; i++) { scanf("%f", &price[i]); total += price[i]; }
    printf("Total: Rs %.2f\n", total);
    free(price);

    // 2. count grades A-E with calloc (all counters start at 0)
    int *count = calloc(5, sizeof(int));
    if (count == NULL) return 1;
    char g;
    for (int i = 0; i < 6; i++) { scanf(" %c", &g); count[g - 'A']++; }
    for (int i = 0; i < 5; i++) printf("%c: %d\n", 'A' + i, count[i]);
    free(count);

    // 3. read marks until -1, growing with realloc
    int cap = 2, used = 0, mark;
    int *marks = malloc(cap * sizeof(int));
    if (marks == NULL) return 1;
    while (scanf("%d", &mark) == 1 && mark != -1) {
        if (used == cap) {
            int *bigger = realloc(marks, cap * 2 * sizeof(int));
            if (bigger == NULL) { free(marks); return 1; }
            marks = bigger;
            cap *= 2;
        }
        marks[used++] = mark;
    }
    printf("Read %d marks (room for %d):", used, cap);
    for (int i = 0; i < used; i++) printf(" %d", marks[i]);
    printf("\n");
    free(marks);
    return 0;
}

Input:

3
120 45.5 30
A B A C E A
70 85 90 60 75 -1

Output:

Total: Rs 195.50
A: 3
B: 1
C: 1
D: 0
E: 1
Read 5 marks (room for 8): 70 85 90 60 75

Doubling the capacity (2 → 4 → 8) means realloc is called only a few times even for thousands of marks.

Task 4, the leaky loop:

for (int day = 1; day <= 1000; day++) {
    char *report = malloc(1000000);   // 1 MB report
    /* ... fill and print the report ... */
}                                     // leak: 1000 MB never returned

Fix: add free(report); at the end of the loop body, so each day's megabyte is returned before the next one is rented.

Quick quiz

What does this print?

int *p = calloc(4, sizeof(int));
p[1] = 5;
printf("%d %d", p[0] + p[1], p[3]);
  • A. junk 5
  • B. 5 junk
  • C. 5 0
  • D. 0 0
Answer

C: 5 0. calloc zeroes the whole block, so p[0] and p[3] are 0, and p[0] + p[1] is 0 + 5 = 5. (Verified output: 5 0.) With malloc, p[0] and p[3] would be junk.

Interview questions

  • What is the difference between the stack and the heap?
  • What does malloc return? What does it return when it fails?
  • What is the difference between malloc and calloc?
  • What does realloc do? Why should you store its result in a temporary pointer?
  • Can realloc move a block? What happens to the old pointer?
  • What is a memory leak? How do you find one (tools like valgrind and AddressSanitizer, coming in episode 26)?
  • What is a dangling pointer? What is a double free?
  • What does free(NULL) do?
  • Why is returning the address of a local variable wrong? How do you return an array from a function?
  • Why do we write n * sizeof(int) instead of n * 4?

Glossary

Term Meaning Example
Fixed (static) size A size written in the code, decided before the program runs int marks[5];
Dynamic memory Memory asked for while the program runs malloc(n * sizeof(int))
Stack The small memory area for local variables, freed automatically when a function returns int marks[5]; inside main
Heap The large memory area for blocks you request and free yourself a malloc block
Stack smashing Writing past a local array and damaging the stack; caught by gcc's stack protector *** stack smashing detected ***
Segmentation fault The operating system stops a program that touched memory it may not use a 40 MB local array
Undefined behaviour Code whose result the C standard doesn't define: it may work, print junk or crash writing marks[7] in a 5-box array
<stdlib.h> The header that declares malloc, calloc, realloc and free #include <stdlib.h>
malloc Rents a block of the given number of bytes; contents are not cleared malloc(8 * sizeof(int))
sizeof The size of a type or variable, in bytes sizeof(int) is 4
void * A pointer with no type: just an address what malloc returns
NULL A pointer to nothing; returned when an allocation fails if (p == NULL)
calloc Rents count items of size bytes and fills them with zeros calloc(6, sizeof(int))
realloc Resizes a block, keeping its data; may move it realloc(marks, 5 * sizeof(int))
free Returns a block to the heap free(marks);
Block One piece of heap memory returned by an allocation the 32 bytes for 8 marks
Memory leak Memory that was allocated and never freed malloc in a loop with no free
Double free Calling free twice on the same block free(p); free(p);
Dangling pointer A pointer that still holds the address of freed (or gone) memory p after free(p)
Variable-length array (VLA) A local array whose size comes from a variable (C99); still on the stack int list[n];
Capacity How many items a block has room for (vs how many are used) cap in the practice solution

Summary

  • An array's size is fixed when you write the code, and local arrays live on the small stack: too small overflows, too big crashes.
  • Dynamic memory comes from the heap, asked for while the program runs.
  • malloc(n * sizeof(type)) rents a block; always check for NULL; use it like an array.
  • malloc gives junk; calloc(count, size) gives zeros.
  • realloc grows a block and keeps the data; store its result in a temporary pointer.
  • Return heap memory from functions, never a local array's address; the caller frees it.
  • Every malloc needs exactly one free; then set the pointer to NULL.

Next episode: File handling: fopen, fprintf, fgets and fclose, so your data survives after the program ends.