119. Borrowed Interface Lifetime Safety

In embedded firmware, framework or middleware code often borrows a driver interface (via a base-class pointer or reference) without owning the driver object itself.
If object lifetime is not managed carefully, the framework may call into a driver after the driver object has already gone out of scope, resulting in undefined behavior.

You are given a firmware-style C++ program where:

  • A framework stores a borrowed base-class pointer to a driver
  • The selected driver object is created in a limited scope
  • The framework later invokes the driver through the base-class interface

Although the program compiles and may appear to run correctly, the design is unsafe and can result in a dangling pointer.

Your task is to correct the program design so that:

  • Runtime polymorphism is preserved
  • The borrowed interface is never used after the driver object is destroyed
  • Object ownership and lifetime are explicit, deterministic, and safe
  • The solution follows embedded firmware constraints

Input / Program Flow

  • Read one integer from standard input

Driver selection rules:

  • If the input value is 0 → use the SPI driver
  • If the input value is 1 → use the I2C driver

Program flow:

  1. Read one integer value
  2. Create the selected driver
  3. Register the driver with framework code using a base-class reference
  4. Framework code invokes the driver through the interface
  5. Program exits without accessing a destroyed object

Output

If the input is 0, output:

SPI transfer completed

If the input is 1, output:

I2C transfer completed

Output Requirements

  • Exactly one line of output
  • Output text and spacing must match exactly
  • Output must be produced via a polymorphic call
  • No extra whitespace or lines

Constraints

  • Language standard: C++11
  • Do NOT use dynamic memory allocation (new, delete)
  • Do NOT use STL containers
  • Do NOT change function names
  • Runtime polymorphism must be preserved
  • Object lifetime must be deterministic and safe
  • Solution must be suitable for embedded / firmware systems

 

 

 

 

Loading...

Input

0

Expected Output

SPI transfer completed