19.3 Comparing C and C++ Approaches

Memory management has developed considerably across languages.
In C, it relies entirely on manual allocation and deallocation, which is prone to mistakes.
Modern C++ improves on this by providing standard smart pointers that help manage memory automatically.
Rust takes the concept further by enforcing ownership and borrowing rules at compile time, eliminating many classes of memory errors before the program even runs.

19.3.1 C

  • Heavy reliance on raw pointers and manual allocation (malloc(), calloc(), realloc()) and deallocation (free()).
  • Frequent pitfalls: double frees, memory leaks, and dangling pointers are common without vigilance.

19.3.2 C++ Smart Pointers

  • C++ provides std::unique_ptr, std::shared_ptr, and std::weak_ptr to automate new/delete.
  • Reference counting and move semantics reduce manual mistakes.
  • Cycles and certain subtle bugs can still appear if not used carefully (e.g., shared pointers forming cycles).

19.3.3 Rust’s Strategy

  • Rust’s smart pointers go further by strictly enforcing borrowing rules at compile time.
  • Where dynamic checks are needed (e.g., interior mutability), Rust panics rather than creating silent runtime corruption.
  • Rust also avoids raw pointers in safe code, thus reducing the scope of errors from manual misuse.