79. Deep Copy Constructor

#include <iostream>
#include <cstdint>
using namespace std;

class SensorData {
private:
    uint8_t* data;  // dynamic array of 8 bytes

public:
    // Constructor: allocate and copy from input array
    SensorData(uint8_t arr[8]) {
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) {
            data[i] = arr[i];
        }
    }

    // Copy constructor: deep copy
    SensorData(const SensorData& other) {
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) {
            data[i] = other.data[i];
        }
    }

    // Destructor: free allocated memory
    ~SensorData() {
        delete[] data;
    }

    void setIndex3() {
        data[3] = 99;
    }

    void print() const {
        for (int i = 0; i < 8; i++) {
            cout << (int)data[i] << (i == 7 ? "" : " ");
        }
        cout << endl;
    }
};

int main() {
    uint8_t arr[8];
    for (int i = 0; i < 8; i++) {
        int temp;
        cin >> temp;
        arr[i] = static_cast<uint8_t>(temp);
    }

    SensorData a(arr);
    SensorData b = a;

    b.setIndex3();

    a.print();
    b.print();

    return 0;
}

Explanation & Logic Summary:

  • The class owns heap-allocated memory (new[])
  • The default copy constructor would perform a shallow copy, causing both objects to share the same buffer
  • A correct copy constructor must:
    • Allocate its own buffer
    • Copy all bytes from the source object
  • The destructor ensures memory is released once per object

With a deep copy:

  • Modifying b does not affect a
  • No double-free occurs
  • Program behavior is deterministic and safe

Firmware Relevance & Real-World Context:
In embedded systems, this pattern appears in:

  • Driver-level data buffers
  • Protocol frame builders
  • Heap-allocated DMA descriptors
  • C++ wrappers over C-based APIs

Incorrect copy behavior can cause:

  • Double free
  • Heap corruption
  • Random system crashes
  • Silent data corruption

This problem reinforces:

  • Copy constructor semantics
  • Deep vs shallow copy
  • Resource ownership
  • Safe dynamic memory handling in Embedded C++

 

 

 

 

Loading...

Input

1 2 3 4 5 6 7 8

Expected Output

1 2 3 4 5 6 7 8 1 2 3 99 5 6 7 8