Reading history

Dynamic Memory in C: malloc, calloc, realloc and free

7 min read 2 views

Allocate memory at run time in C with malloc, calloc and realloc, and release it with free. Examples, a growing array, and how to avoid leaks.

An ordinary array needs its size fixed when you write the program. But often you only find out how much data there is while the program runs: how many students are in a class, how long a file is, how many readings a sensor sends. Dynamic memory allocation lets a program ask for exactly the memory it needs at run time, and hand it back when it is done.

In this lesson you will learn

  • The difference between stack memory and heap memory
  • How to use malloc, calloc, realloc and free
  • How to build an array that grows as data arrives
  • The four classic memory bugs and how to avoid them
  • Tools that find memory bugs for you

Why Programs Need Memory at Run Time

Local variables live on the stack. Stack memory is fast and automatic: it appears when a function starts and disappears when it returns. But it has two limits. Its size is fixed at compile time, and it is small, often just a few megabytes.

The heap is a much larger pool of memory that your program manages by hand. You ask for a block with malloc and friends, use it for as long as you like, even after the function that created it has returned, and release it with free. All four functions are declared in <stdlib.h>.

StackHeap
Size decidedWhen you compileWhile the program runs
LifetimeUntil the function returnsUntil you call free
Typical capacityA few megabytesMost of the computer’s free memory
Who cleans upThe compiler, automaticallyYou

See memory layout of a C program for where each region sits.

malloc, calloc, realloc and free

malloc: Ask for a Block

malloc(bytes) returns a pointer to a block of that many bytes, or NULL if the memory is not available. The block’s contents are not cleared, so it holds leftover garbage until you write to it.

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

/* The class size is only known while the program runs. */
int main(void) {
    int n = 5;                                   /* imagine this came from the user */
    int *marks = malloc(n * sizeof *marks);
    if (marks == NULL) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }
    int sample[] = {72, 85, 64, 90, 78};
    int total = 0;
    for (int i = 0; i < n; i++) {
        marks[i] = sample[i];
        total += marks[i];
    }
    printf("%d students, average %.1f\n", n, (double)total / n);
    free(marks);                                 /* give the memory back */
    marks = NULL;                                /* avoid a dangling pointer */
    return 0;
}

Output

5 students, average 77.8

Three habits from this example are worth copying every time:

  • Write the size as n * sizeof *marks. If you later change the type of marks, the size stays correct automatically.
  • Check for NULL before using the memory.
  • Call free when you are finished, then set the pointer to NULL.

calloc: Ask for a Cleared Block

calloc(count, size) allocates room for count items of size bytes and fills every byte with zero. That is ideal for counters.

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

int main(void) {
    int *counts = calloc(6, sizeof *counts);     /* six zeros, ready to use */
    if (!counts) return 1;
    int rolls[] = {3, 6, 3, 1, 6, 6, 2};
    for (int i = 0; i < 7; i++) counts[rolls[i] - 1]++;
    for (int face = 1; face <= 6; face++)
        printf("face %d: %d\n", face, counts[face - 1]);
    free(counts);
    return 0;
}

Output

face 1: 1
face 2: 1
face 3: 2
face 4: 0
face 5: 0
face 6: 3

With malloc, the counts would start as random values and the tally would be wrong.

realloc and free

  • realloc(ptr, new_bytes) resizes a block. It may grow it in place, or move the data to a new, larger block and free the old one. Either way, use the pointer it returns.
  • free(ptr) returns the block to the heap. Freeing NULL is allowed and does nothing.

Building a Growing Array With realloc

When you do not know how much data is coming, start small and double the capacity each time the array fills up.

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

/* A list that grows as data arrives: double the capacity when it is full. */
int main(void) {
    size_t size = 0, capacity = 2;
    int *temps = malloc(capacity * sizeof *temps);
    if (!temps) return 1;

    int readings[] = {31, 33, 29, 35, 36, 34, 30};
    for (int i = 0; i < 7; i++) {
        if (size == capacity) {
            capacity *= 2;
            int *bigger = realloc(temps, capacity * sizeof *bigger);
            if (!bigger) { free(temps); return 1; }   /* old block is still valid */
            temps = bigger;
            printf("grew to capacity %zu\n", capacity);
        }
        temps[size++] = readings[i];
    }
    printf("stored %zu readings:", size);
    for (size_t i = 0; i < size; i++) printf(" %d", temps[i]);
    printf("\n");
    free(temps);
    return 0;
}

Output

grew to capacity 4
grew to capacity 8
stored 7 readings: 31 33 29 35 36 34 30

Notice that the result of realloc goes into a new variable, bigger. If realloc fails it returns NULL but leaves the old block untouched. Writing temps = realloc(temps, ...) directly would overwrite your only pointer to that block and leak it.

Doubling, rather than adding one slot at a time, keeps the number of resizes small. The average cost per insert stays constant, as explained in amortized analysis.

Leaks, Dangling Pointers and Double Free

BugWhat happensTypical causePrevention
Memory leakMemory is never returned; a long-running program slowly uses more and moreLosing the last pointer to a block, or returning early without freeGive every malloc a matching free on every path
Dangling pointerUsing memory after it was freed; may crash or silently corrupt dataKeeping a pointer after freeSet pointers to NULL after freeing
Double freeFreeing the same block twice; can corrupt the heap or crashTwo pointers to one block, both freedDecide clearly which part of the code owns each block
Buffer overflowWriting past the end of the blockWrong size calculation, often a forgotten sizeofAlways multiply by sizeof the element

These bugs often do not crash straight away, which makes them hard to find. Two free tools catch them for you:

  • AddressSanitizer: compile with gcc -g -fsanitize=address prog.c. The program stops at the exact line of a bad access.
  • Valgrind: run valgrind --leak-check=full ./prog on Linux to get a report of every leaked block.

Dynamic Memory Rules to Follow

  1. Include <stdlib.h>. In C you do not need to cast the result of malloc.
  2. Size allocations with count * sizeof *ptr.
  3. Check every result for NULL.
  4. Use calloc when you need the memory to start at zero.
  5. Assign realloc‘s result to a temporary pointer first.
  6. Free exactly once, and set the pointer to NULL afterwards.
  7. Never free memory you did not allocate, such as a local array or a string literal.

Practice Exercises

Exercise 1. What is wrong with int *p = malloc(10); for storing 10 integers?

Show answer

It allocates 10 bytes, not 10 integers. With 4-byte ints it holds only 2. Write malloc(10 * sizeof *p).

Exercise 2. Find the bug:

char *name = malloc(20);
strcpy(name, "Karim");
free(name);
printf("%s\n", name);
Show answer

It uses name after freeing it, a dangling pointer. Print before calling free.

Exercise 3. Why is data = realloc(data, newsize); risky?

Show answer

If realloc fails, it returns NULL and data loses the only pointer to the original block, which then leaks. Store the result in a temporary pointer and check it first.

Frequently Asked Questions

What is the difference between malloc and calloc?

malloc takes a total size in bytes and leaves the memory uninitialised. calloc takes a count and an item size, and sets every byte to zero.

Does the operating system free memory when my program ends?

On desktop systems, yes. But a program that runs for days, such as a server, must free memory as it goes or it will eventually run out.

Should I cast the result of malloc in C?

No. In C, void * converts to any object pointer automatically. A cast can hide a missing #include <stdlib.h>. (C++ is different and does need the cast.)

Can malloc really return NULL?

Yes, when memory runs out or the requested size is unreasonable. It is rare on desktops but common on small embedded devices, so always check.

Summary

  • Heap memory is requested at run time and lasts until you free it.
  • malloc allocates, calloc allocates and zeroes, realloc resizes, free releases.
  • Always size with sizeof, check for NULL and free exactly once.
  • Grow arrays by doubling, and keep realloc‘s result in a temporary pointer.
  • Use AddressSanitizer or Valgrind to catch leaks and bad accesses.
Lessons are also marked complete when you click Next.