malloc and free
Allocate on the heap.
malloc and free is a free C Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, and your progress syncs across the web and the CoddyKit app. The C Academy course includes 4 lessons in total.
The Heap
So far variables lived on the stack with a fixed lifetime. The heap lets you request memory at runtime and keep it as long as you need.
You manage heap memory yourself using <stdlib.h> functions.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 99;
printf("%d\n", *p);
free(p);
return 0;
}Calling malloc
malloc(size) reserves size bytes and returns a pointer to them, or NULL on failure.
The memory is uninitialized: its contents are indeterminate.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 7;
printf("value = %d\n", *p);
free(p);
return 0;
}Sizing with sizeof
Always size allocations with sizeof so the code is correct on any platform.
Writing sizeof(*p) ties the size to the pointer's type automatically.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double *p = malloc(sizeof(*p));
*p = 3.14;
printf("%f\n", *p);
free(p);
return 0;
}Always Check for NULL
If allocation fails, malloc returns NULL. Dereferencing it crashes the program.
Check the result before using it.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
if (p == NULL) {
printf("allocation failed\n");
return 1;
}
*p = 5;
printf("ok: %d\n", *p);
free(p);
return 0;
}Allocating an Array
To hold many elements, multiply the element size by the count.
malloc(n * sizeof(int)) creates room for n integers.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *arr = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) arr[i] = i * i;
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}Heap Arrays Use Pointer Indexing
A heap array is accessed through its pointer with the familiar arr[i] syntax, which is the same as *(arr + i).
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(3 * sizeof(int));
arr[0] = 10;
*(arr + 1) = 20;
arr[2] = 30;
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
free(arr);
return 0;
}Freeing Memory
free(p) returns the block to the allocator. After this you must not use p to access that memory.
Every successful malloc needs a matching free.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *buf = malloc(16);
if (buf) {
buf[0] = 'A';
printf("%c\n", buf[0]);
free(buf);
}
return 0;
}free(NULL) Is Safe
Calling free on a NULL pointer does nothing and is perfectly legal.
This simplifies cleanup code that may run before allocation succeeds.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = NULL;
free(p);
printf("free(NULL) was safe\n");
return 0;
}Returning Heap Memory
Unlike stack variables, heap memory survives after the function returns. This lets a function allocate and hand back a buffer.
#include <stdio.h>
#include <stdlib.h>
int *make_range(int n) {
int *a = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) a[i] = i;
return a;
}
int main(void) {
int *r = make_range(4);
printf("%d %d\n", r[0], r[3]);
free(r);
return 0;
}Do Not Cast malloc in C
In C, malloc returns a void * that converts to any pointer type automatically.
Casting it is unnecessary and can hide a missing <stdlib.h> include.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
long *p = malloc(sizeof(long));
*p = 1234567L;
printf("%ld\n", *p);
free(p);
return 0;
}Don't Free Twice
Calling free on the same pointer twice is undefined behavior and can corrupt the heap.
Set the pointer to NULL after freeing to make accidental reuse harmless.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 1;
free(p);
p = NULL;
free(p);
printf("no double free\n");
return 0;
}Quick Check
Test your knowledge of malloc and free.
Recap
You learned heap allocation basics:
malloc(size)reserves uninitialized bytes, returningNULLon failure.- Always check the result and size with
sizeof. free(p)returns memory; every malloc needs one free.free(NULL)is safe; double free is undefined.
Learn C with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 39
- Lessons
- 144
Frequently Asked Questions
Is the “malloc and free” lesson free?
Yes — the full text of “malloc and free” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO. The C Academy course includes 4 lessons in total.
What will I learn in “malloc and free”?
Allocate on the heap. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C Academy?
No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “malloc and free” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C Academy lesson?
Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- malloc and free
- calloc and realloc
- Memory Leaks
- Dangling Pointers