free
- C course
- Beginner
- Lesson 103/116
- 5 min
Learn to release allocated memory with free.
free: releasing heap memory
Memory allocated with malloc must be released with free. Otherwise a memory leak occurs.
int *p = malloc(sizeof(int));
*p = 50;
printf("%d\n", *p);
free(p); /* give the memory back */Here the free(p) call returns the heap area to the operating system. p itself is still a valid pointer; but the place it points to is no longer yours. Using that pointer after free is a use after free error.
Avoiding memory leaks
Every malloc must have a matching free. Memory allocated and never released during the program is a leak.
for (int i = 0; i < 100; i++) {
int *p = malloc(sizeof(int));
/* use */
free(p); /* release each iteration */
}Here each loop iteration has one malloc and one free; this balance prevents leaks. In long-running programs leaks accumulate and eventually memory runs out. So never forgetting free is very important.
Practice malloc, use, free
Allocate an int with malloc; assign *p = 50; print with printf; finally release the memory with free. Include the <stdlib.h> header.
Starter code
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Allocate an int with malloc; *p = 50; print with printf; release with free */
return 0;
}Sample solution
int *p = malloc(sizeof(int));
*p = 50;
printf("%d\n", *p);
free(p);Expected output
50
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the purpose of free?
- Allocate memory
- Resize memory
- Reset a pointer
- Release allocated memory Correct answer
Explanation: free gives back memory allocated with malloc.
2 Match function to task
| Term | Meaning |
|---|---|
malloc |
Allocates memory |
free |
Releases memory |
sizeof |
Gives byte size |
use after free |
Error case |
3 Fill in the blank: free call
int *p = malloc(sizeof(int));
*p = 50;
____(p);
int *p = malloc(sizeof(int));
*p = 50;
free(p);
Explanation: free(p) releases the heap memory.