29. Safe Sensor nullptr Check

#include <iostream>
using namespace std;

int main() {
    int flag;
    cin >> flag;

    int* sensorPtr = nullptr;

    if (flag == 1) {
        sensorPtr = new int;
        cin >> *sensorPtr;
    }

    if (sensorPtr == nullptr) {
        cout << "NO SENSOR";
    } else {
        cout << *sensorPtr;
    }

    delete sensorPtr;
    return 0;
}

Explanation & Logic Summary:

  • sensorPtr starts as nullptr to indicate absence of hardware
  • Memory is allocated only when the sensor is reported as connected
  • A nullptr check prevents unsafe dereferencing
  • delete on a null pointer is safe and deterministic

Firmware Relevance & Real-World Context:

  • Optional peripherals are common in embedded systems
  • nullptr cleanly represents unavailable hardware
  • Prevents null dereference crashes (critical firmware faults)
  • Common patterns include:
    • HAL optional drivers
    • RTOS object handles
    • Callback and resource pointers

 

 

 

 

Loading...

Input

0

Expected Output

NO SENSOR