CodeBlanks Logo Icon CodeBlanks

valgrind

  • C course
  • Intermediate
  • Lesson 97/116
  • 5 min

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.

Practice 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);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// Allocate a 3-element int array
// Assign 10, 20, 30 to the elements
// Print the sum
// Free the memory

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

60

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What kind of errors does valgrind catch?

  • Syntax errors
  • Type mismatches
  • Compiler warnings
  • Memory leaks Correct answer

Explanation: valgrind catches memory leaks and uninitialized reads.

2 Match the memory management

Term Meaning
malloc Allocate memory
free Release memory
sizeof(int) Type size
--leak-check Leak check

3 Complete the malloc call

Question
int *arr = malloc(3 * sizeof(____));
Answer
int *arr = malloc(3 * sizeof(int));

Explanation: sizeof(int) gives the byte size of the int type.

All lessons in Intermediate