Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#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] << " "; // 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 "; return 0; }
Result
Open