KatInterview

Low-Level Generics in C vs RAII and Smart Pointers in C++

System DesignModel answer
MediumModel answerSystem Designccppmemory-management

Last updated

Compare low-level C abstractions (type erasure, macros, linkages) with C++ resource management model (RAII, smart pointer memory layouts, and weak_ptr lifecycle dynamics).

Context

Developing high-performance systems software requires balancing flexible design patterns with explicit memory management. While C relies on programmer discipline, manual idioms, and textual expansion, modern C++ leverages strict type systems and smart pointer ownership semantics.

Explain the mechanics of generic abstraction in C and the modern ownership models in C++. Address all of the following prompts structured into two parts:

Part 1: Generic Data Structures and Mechanics in C

  1. Describe the three primary mechanisms used to achieve generic code in C: type erasure via void* and function callbacks (e.g., standard libraries like qsort), textual generation via preprocessor macros, and type-dispatching with C11 _Generic.
  2. Explain the fundamental reasons why C lacks built-in function overloading, explicitly detailing compiler symbol resolution, linkage rules, and binary compatibility across translation units.
  3. Compare void* pointer-based generics against macro-expanded compile-time generics across type safety, runtime overhead, binary code size, and developer ergonomics.

Part 2: Modern C++ Resource Management and Smart Pointers

  1. Explain the Resource Acquisition Is Initialization (RAII) idiom. Contrast the ownership guarantees of std::unique_ptr and std::shared_ptr, explaining why move semantics are mandatory for unique ownership.
  2. Outline the internal memory layout of a std::shared_ptr, detailing the components of the control block, the distinction between strong and weak ref-counts, and the operational differences between std::make_shared and explicit raw pointer construction.
  3. Describe how reference cycles cause memory leaks under shared ownership, explain how std::weak_ptr resolves cycle issues, and demonstrate how a std::weak_ptr safely queries and accesses object memory.

Expected Formatting

Provide clear explanations organized systematically by part and prompt. Include representative C code snippets (such as custom comparators and macro structures) and modern C++ code snippets (such as non-owning std::weak_ptr::lock usage).

Hints

Hint 1

Recall how the compiler links symbol names in C vs C++ name mangling.

Hint 2

Consider how many allocations occur when using std::make_shared vs std::shared_ptr(new T()).

Hint 3

Think about what happens to the control block vs the underlying object when strong count hits 0 but weak count is greater than 0.