C++
Beginner
1 min read
Memory Leaks, Valgrind, and Address Sanitizer
Example
#include <iostream>
#include <vector>
#include <memory>
// DEMONSTRATES: what leaks look like and how to fix them
// BAD: leaks on exception path
void leaky(bool throwIt) {
int* data = new int[1024];
if (throwIt) throw std::runtime_error("oops");
delete[] data; // never reached if exception thrown
}
// GOOD: RAII via vector — never leaks
void safe(bool throwIt) {
std::vector<int> data(1024); // owns memory via RAII
if (throwIt) throw std::runtime_error("oops");
// data freed automatically whether or not exception thrown
}
// Demonstrates use-after-free (undefined behaviour — don't do this)
void useAfterFree() {
int* p = new int(42);
delete p;
// std::cout << *p; // UB: reading freed memory
}
int main() {
// Safe version handles exception cleanly
try { safe(true); } catch (...) {}
// Smart pointer — zero manual memory management
auto buf = std::make_unique<int[]>(1024);
buf[0] = 99;
std::cout << "buf[0] = " << buf[0] << "\n";
// buf freed here automatically
// Compile with: g++ -fsanitize=address -g -o prog prog.cpp
// Run: ./prog (ASan reports any detected errors)
std::cout << "No leaks with RAII and smart pointers\n";
return 0;
}