C
valgrind
Learn to find memory errors with valgrind.
Memory checks with valgrind
valgrind inspects a program's memory use at run time. Its most common use is finding leaks: valgrind --leak-check=full ./program.
valgrind runs the program slowly but checks that every malloc has a matching free. If there is a leak, the report shows a "definitely lost" line with the byte count. It also catches reads of uninitialized variables and out-of-bounds array access. These checks cannot be caught by the compiler; they appear only at run time. So valgrind should be run regularly on any C program that uses dynamic memory.
A leak-free program
For valgrind to report clean, every malloc must have a matching free. Free the memory as soon as you are done with it.
Example: int *arr = malloc(3 * sizeof(int)); allocates room for three integers. After filling the values you compute the sum and release the memory with free(arr);. sizeof(int) gives the type size so the code works across platforms. Forgetting free causes a leak; calling it too early causes a dangling pointer. The correct order is: allocate, use, free.
Exercise Write a leak-free program
Allocate a three-element array with int *arr = malloc(3 * sizeof(int));. Assign arr[0] = 10; arr[1] = 20; arr[2] = 30;. Compute int sum = arr[0] + arr[1] + arr[2];. Print with printf("%d\n", sum);. Finally release the memory with free(arr);.
Show example solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(3 * sizeof(int));
arr[0] = 10; arr[1] = 20; arr[2] = 30;
int sum = arr[0] + arr[1] + arr[2];
printf("%d\n", sum);
free(arr);
return 0;
}
Test yourself
-
What kind of errors does valgrind catch?
- Syntax errors
- Type mismatches
- Compiler warnings
- Memory leaks
Show answer
Memory leaks — valgrind catches memory leaks and uninitialized reads.
-
Match the memory management
- malloc
- Allocate memory
- free
- Release memory
- sizeof(int)
- Type size
- --leak-check
- Leak check
-
Complete the malloc call
int *arr = malloc(3 * sizeof(____));
Show answer
int *arr = malloc(3 * sizeof(int));
Next lesson: printf debugging