Course contentsShow
← C
Lesson 568 of 1,2198. Memory ManagementFree lesson

Finding invalid reads and writes

Finding invalid reads and writes

What you'll learn: How to use Valgrind to identify when your program attempts to access memory it doesn't own.

Imagine your computer's memory is a massive hotel. When you use malloc, the clerk gives you a room key (a pointer) and says, "You have access to room 402." An invalid read or write happens when you try to barge into room 403 or try to sleep in the hallway. You don't have the key for those spots, and in the world of C, this leads to unpredictable crashes and security holes.

The "Off-by-One" Nightmare

The most common way to trigger an invalid access is by stepping just outside the bounds of an array. Because C doesn't stop you from reaching past the end of a buffer, the program might seem to work fine until it suddenly doesn't.

#include <stdlib.h>

int main() {
    int *numbers = malloc(3 * sizeof(int));
    
    // We allocated space for indices 0, 1, and 2.
    // Accessing index 3 is an "Invalid Write"
    numbers[3] = 42; 

    free(numbers);
    return 0;
}

Reading the Valgrind Map

When you run your program through Valgrind using valgrind ./my_program, it acts like a security guard watching your every move. If you touch memory you shouldn't, Valgrind shouts.

You will typically see an error like:
Invalid write of size 4

This tells you exactly how many bytes you tried to change (4 bytes for an int). Below that, Valgrind provides a stack trace, showing the specific function and line number where the trespass occurred.

An Invalid Read means you tried to look at data you don't own, while an Invalid Write means you tried to change it. Both are "memory errors," and even if your program doesn't crash immediately, these errors are ticking time bombs. By fixing every invalid access Valgrind reports, you ensure your program stays within its assigned "hotel rooms," making it stable and secure.

Key takeaway

Invalid reads and writes occur when you access memory outside of your allocated blocks, and Valgrind is the essential tool for pinpointing the exact line where these boundaries are crossed.