Intermediate · Dynamic memory · topic 27 of 60 · 30 min
malloc, calloc and free
Explanation
malloc
#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
double *totals = calloc(12, sizeof *totals); /* 12 doubles, all 0.0 */
if (!totals) return 1;free
free(marks); /* give the block back to the allocator */
marks = NULL; /* prevent accidental reuse (free(NULL) is a harmless no-op) */| Rule | Why |
|---|---|
| Free every block exactly once | Missing free = leak; second free = double free (undefined behaviour) |
| Free only what malloc/calloc/realloc returned | Freeing a stack address, a string literal or a pointer into the middle of a block is undefined |
| Do not use memory after free | The block may be reused for something else (use-after-free) |
| Check every allocation for NULL | Allocation can fail, especially on embedded systems |
| Set the pointer to NULL after free | Turns accidental reuse into an immediate, obvious crash |
Allocating a struct
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).
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
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.
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)
Which allocation is correct and robust for an array of n doubles?
Which line has the bug? 1: char *s = malloc(10); 2: strcpy(s, "hi"); 3: free(s); 4: printf("%s\n", s);
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- realloc and growing arraysDynamic memory · same module
- Memory leaks and other heap bugsDynamic memory · same module
- C interview questionsEmbedded C, system calls and careers
- Pointers to structs and the arrow operatorStructs, unions, enums and files
- Memory 101: the stack and the heapRust Programming · Ownership: Rust's big idea
- Addresses and pointersPointers
Questions people ask about this
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
What does a double free usually cause?Related
Answer: Heap corruption, often a crash or a security hole
The allocator's bookkeeping is corrupted.
On a little-endian machine, which byte of uint32_t x = 0x11223344 is stored first in memory?Related
How many frees does an array of 5 row pointers (each row malloc'd) need?Related
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
- 3 more topics in “Dynamic memory” before its exam: realloc and growing arrays, Memory leaks and other heap bugs, Dynamic strings and 2D arrays.
- Module 6 exam: Dynamic memory · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Structs, unions, enums and files. 60 topics left in the course before the final exam.