Skip to content

Intermediate · Dynamic memory · topic 27 of 60 · 30 min

malloc, calloc and free

Explanation

malloc(n) returns a pointer to n bytes of uninitialised heap memory, or NULL if it fails. calloc(count, size) allocates and zeroes. free(p) returns the block; call it exactly once per allocation, and never on memory you did not allocate. Use the p = malloc(n * sizeof *p) idiom, check for NULL, and set p = NULL after free.

malloc

c
#include <stdlib.h>

int n = 100;
int *marks = malloc(n * sizeof *marks);   /* sizeof *marks = size of ONE int */
if (marks == NULL) {
    fprintf(stderr, "Out of memory\n");
    return 1;
}
marks[0] = 78;          /* use it like an array */
/* marks[1] … marks[99] contain garbage until you set them */

malloc returns void *, which converts automatically to any object pointer type in C, so no cast is needed (a cast is required in C++, which is why you see one in some code). Writing sizeof *marks instead of sizeof(int) keeps the code correct if the type of marks ever changes.

calloc: allocate and zero

c
double *totals = calloc(12, sizeof *totals);   /* 12 doubles, all 0.0 */
if (!totals) return 1;
calloc also checks the count × size multiplication for overflow in common implementations, which malloc(count * size) does not.

free

c
free(marks);      /* give the block back to the allocator */
marks = NULL;     /* prevent accidental reuse (free(NULL) is a harmless no-op) */
RuleWhy
Free every block exactly onceMissing free = leak; second free = double free (undefined behaviour)
Free only what malloc/calloc/realloc returnedFreeing a stack address, a string literal or a pointer into the middle of a block is undefined
Do not use memory after freeThe block may be reused for something else (use-after-free)
Check every allocation for NULLAllocation can fail, especially on embedded systems
Set the pointer to NULL after freeTurns accidental reuse into an immediate, obvious crash

Allocating a struct

c
struct Order { int id; double amount; char status[12]; };

struct Order *o = malloc(sizeof *o);
if (!o) return 1;
o->id = 1042;               /* -> accesses a member through a pointer (module 7) */
o->amount = 1499.0;
strcpy(o->status, "PAID");
free(o);

Ownership

In larger programs the key question for every heap pointer is "who owns this, and who frees it?" A common convention: the function or module that allocates provides a matching function to free (create_order / destroy_order), and documentation says when the caller must call it. Mixing up ownership causes leaks (nobody frees) or double frees (two parts free).

Careful: malloc does not zero memory. Reading malloc'd memory before writing it gives garbage and is a common source of "random" bugs; valgrind reports "Conditional jump or move depends on uninitialised value(s)". Use calloc when you need zeros, or initialise immediately.
Think of it like this: malloc is like borrowing a numbered locker from a station's cloak room: you get a token (the pointer), the locker may still have someone's old wrappers inside (garbage), and you must return the token exactly once (free). Returning it twice, or using the locker after returning it, causes trouble for whoever gets it next.
Tip: Write the free at the same time as the malloc (for example at the end of the same function, or in a matching destroy function), so you never forget it.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

malloc, calloc and free · 1/6

malloc and free

In this lesson you will allocate and free heap memory.

Prefer a video by a teacher? Find free videos on “c malloc calloc free tutorial memory allocation” on YouTube ↗

In real life: A product record created on demand

An inventory service creates a product record when a new item is scanned for the first time. A constructor-style function allocates and fills the struct, and a matching function frees it, so ownership is clear to everyone on the team.

c
struct Product { char sku[16]; int qty; };

struct Product *product_new(const char *sku) {
    struct Product *p = calloc(1, sizeof *p);      /* zeroed: qty = 0 */
    if (!p) return NULL;
    snprintf(p->sku, sizeof p->sku, "%s", sku);
    return p;
}

void product_free(struct Product *p) { free(p); }

Practice (0/3 done)

Task 1 · Question

Which allocation is correct and robust for an array of n doubles?

Task 2 · Question

Which line has the bug? 1: char *s = malloc(10); 2: strcpy(s, "hi"); 3: free(s); 4: printf("%s\n", s);

Task 3 · Practice

Write struct Student { char name[30]; int *marks; int n; } with functions Student *student_new(const char *name, int n) (allocating the struct AND the marks array, freeing everything if either allocation fails) and void student_free(Student *s). Test it, then run it under valgrind or with -fsanitize=address to confirm no leaks.

Quick quiz

Question 1

1.What does malloc return when it cannot allocate?

Question 2

2.What is the difference between malloc and calloc?

Question 3

3.What does free(NULL) do?

Question 4

4.Is a cast needed on malloc's result in C?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does malloc return when it cannot allocate?

Answer: NULL

Always check.

What is the difference between malloc and calloc?

Answer: calloc zeroes the memory and takes count and size

malloc leaves memory uninitialised.

What does free(NULL) do?

Answer: Nothing (it is allowed)

The standard defines it as a no-op.

Is a cast needed on malloc's result in C?

Answer: No: void * converts automatically (C++ needs the cast)

Leaving it out is idiomatic C.

Who frees heap memory in C?Related

Answer: The program, by calling free

There is no garbage collector.

From Stack and heap

What does a double free usually cause?Related

Answer: Heap corruption, often a crash or a security hole

The allocator's bookkeeping is corrupted.

From Memory leaks and other heap bugs

On a little-endian machine, which byte of uint32_t x = 0x11223344 is stored first in memory?Related

Answer: 0x44

The least significant byte comes first.

From C interview questions

How many frees does an array of 5 row pointers (each row malloc'd) need?Related

Answer: 6

5 rows + the pointer array.

From Dynamic strings and 2D arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Dynamic memory” before its exam: realloc and growing arrays, Memory leaks and other heap bugs, Dynamic strings and 2D arrays.
  2. Module 6 exam: Dynamic memory · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Structs, unions, enums and files. 60 topics left in the course before the final exam.

← Previous: Stack and heap