20. Dynamic Integer Allocation

#include <iostream>
using namespace std;

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

    int* p = new int;   // dynamically allocate an integer
    *p = x;             // store input value

    cout << *p;         // print stored value

    delete p;           // free allocated memory

    return 0;
}

Explanation & Logic Summary:

  • new int dynamically allocates memory on the heap.
  • The value is stored using pointer dereference.
  • Printing *p retrieves the stored value.
  • delete p frees the allocated memory to prevent leaks.

Firmware Relevance & Real-World Context:

  • While many embedded systems avoid dynamic memory, certain environments (RTOS, Linux-based firmware, or configurable modules) may require it.
  • Understanding new / delete is essential for:
    • Memory-managed drivers
    • Dynamic buffers in communication stacks
    • Objects created during runtime events
  • Proper cleanup prevents memory leaks, which are critical in long-running embedded systems.
Loading...

Input

42

Expected Output

42