5.1.19 · HinglishC Programming

Valgrind — detecting memory errors

1,759 words8 min readRead in English

5.1.19 · Coding › C Programming


YEH tool exist kyun karta hai?

C tumhe raw pointers deta hai aur koi automatic memory management nahi hoti. CPU khushi se kisi bhi address par read/write karta hai; agar tumne malloc(10) kiya aur byte 11 likha, toh kuch turant crash nahi hoga — tum heap corrupt karte ho aur program "randomly" 5000 lines baad mar jata hai. Yeh bugs hote hain:

  • Non-deterministic (heap layout aur timing par depend karte hain).
  • Silent (koi compiler warning nahi, aksar koi crash nahi).

YEH kya track karta hai (core trick — shadow memory): Real memory ke har byte ke liye, Memcheck do bits of info rakhta hai:

  • A-bits (Addressability): kya yeh byte abhi access karne ki ijazat hai?
  • V-bits (Validity/defined-ness): kya is byte mein koi defined value hai, ya malloc ki garbage?

HOW Memcheck reason karta hai (first principles se derivation)

Yahan koi formula nahi hai — hamare paas ek decision procedure hai. Isko build karte hain.

Maano address aur access size hai. se shuru hokar bytes ke read ya write ke liye:

Agar koi bhi byte accessible nahi hai ⇒ Invalid read/write error.

Defined-ness ke liye, V-bits operations ke through propagate hote hain. Starting rules:

Leak rule (exit par mark-and-sweep): program khatam hone par, Memcheck ek GC-style scan karta hai. Ek heap block ho sakta hai:

  • Still reachable: koi pointer uski taraf exist karta hai → "lost" leak nahi (lekin phir bhi unfreed).
  • Definitely lost: koi bhi pointer kahin bhi uski taraf point nahi karta → tumne use leak kiya.
  • Indirectly lost: sirf kisi doosre lost block ke through reachable.
  • Possibly lost: sirf koi interior pointer uski taraf point karta hai.
Figure — Valgrind — detecting memory errors

Worked Example 1 — Heap buffer overflow

#include <stdlib.h>
int main(void) {
    int *a = malloc(5 * sizeof(int)); // 20 bytes, A-bits=1, V-bits=undef
    a[5] = 42;                         // writes bytes 20..23 -> A-bits=0!
    free(a);
    return 0;
}

Run: gcc -g -O0 prog.c && valgrind --leak-check=full ./a.out

Valgrind kehta hai:

Invalid write of size 4
   at main (prog.c:4)
 Address 0x... is 0 bytes after a block of size 20 alloc'd

Worked Example 2 — Use of uninitialised value

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *p = malloc(sizeof(int)); // V-bits = undefined
    if (*p == 0)                  // branching on undefined value!
        printf("zero\n");
    free(p);
    return 0;
}
Conditional jump or move depends on uninitialised value(s)

Worked Example 3 — Memory leak

#include <stdlib.h>
int main(void) {
    char *buf = malloc(100);
    buf = malloc(200);   // first 100-byte block now unreachable
    free(buf);           // frees the 200, leaks the 100
    return 0;
}
LEAK SUMMARY:
   definitely lost: 100 bytes in 1 blocks


Recall Ek 12-saal ke bachche ko explain karo (hidden)

Socho tumhe 5 lockers ki ek row mili hai apna saman rakhne ke liye. C tumhe locker number 6 mein cheez daalne deta hai — jo tumhara nahi hai — aur koi rokta nahi. Valgrind ek strict guard hai jo tumhare peeche khada hai. Jab bhi tum ek locker kholte ho, guard check karta hai: "Kya yeh tumhara hai?" (addressability) aur "Kya tumne actually yahan kuch rakha hai, ya yeh khali kachra hai?" (defined-ness). Din ke ant mein guard yeh bhi check karta hai: "Kya tumne apna koi bag bina kisi ko bataye kahin chhod diya?" — woh leaks hain. Program slower chalta hai kyunki guard sab kuch check karta hai, lekin aakhirkar tum apni saari chhipi galtiyan pakad lete ho.


Flashcards

Valgrind ko har memory access dikhane wali virtual machine technique kya hai?
Yeh program ko ek synthetic/virtual CPU (JIT-instrumented) par chalata hai, har load/store ke around checks insert karta hai.
Memcheck mein A-bits aur V-bits kya hain?
A-bits = addressability (kya is byte ko access kiya ja sakta hai?); V-bits = validity/defined-ness (kya ismein koi defined value hai?).
Freed memory ka read kaunse tarah ka error hai?
Ek A-bit (addressability) error → "Invalid read", use-after-free.
Malloc'd-lekin-unwritten variable par branch karna kya trigger karta hai?
Ek V-bit error: "Conditional jump or move depends on uninitialised value(s)".
Valgrind freed blocks ko quarantine freelist mein kyun rakhta hai?
Taaki unke A-bits 0 rahen aur immediately reuse na hon, jisse use-after-free detect ho sake.
"Definitely lost" aur "still reachable" mein fark?
Definitely lost = koi pointer block ki taraf point nahi karta (sachi leak); still reachable = exit par ek pointer abhi bhi exist karta hai (aksar harmless).
Valgrind chalane se pehle -g -O0 se compile kyun karo?
-g report mein source line/variable names deta hai; -O0 optimiser ko buggy access reorder/elide karne se rokta hai.
--track-origins=yes kya add karta hai?
Yeh batata hai ki ek uninitialised value kahan se aayi, slower execution ki qeemat par.
Ek program "theek se chal" sakta hai phir bhi Valgrind error ho sakta hai kyun?
Bug undefined behaviour hai; correct output heap layout/luck par depend karta hai, code ke sahi hone par nahi.
Full leak details dikhane wala flag kaunsa hai?
--leak-check=full (plus --show-leak-kinds=all har category ke liye).

Connections

  • malloc and free — woh allocations jo Valgrind shadow karta hai
  • Pointers in C — invalid/dangling pointers woh hain jo A-bits guard karte hain
  • Undefined Behaviour in C — kyun yeh bugs silent hote hain
  • Stack vs Heap — Memcheck mainly heap ko police karta hai
  • AddressSanitizer (ASan) — compiler-based alternative, faster, alag trade-offs
  • Debugging with GDB — root-cause analysis ke liye Valgrind ke saath pair karo

Concept Map

causes

motivates

default tool

uses

tracks

tracks

detects

detects

quarantines freed blocks

enables catching

scan at exit

classifies

C raw pointers, no auto memory mgmt

Silent non-deterministic memory bugs

Valgrind instrumentation framework

Memcheck

Shadow memory metadata

A-bits Addressability

V-bits Validity

Invalid read/write errors

Use of uninitialised values

Freelist quarantine

Use-after-free

Mark-and-sweep leak check

Definitely / indirectly / possibly lost