82. SensorFrame Deep Copy Fix

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

class SensorFrame {
private:
    uint8_t* data;

public:
    SensorFrame(uint8_t arr[8]) {
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) data[i] = arr[i];
    }

    // Deep-copy constructor
    SensorFrame(const SensorFrame& other) {
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) data[i] = other.data[i];
    }

    // Deep-copy assignment
    SensorFrame& operator=(const SensorFrame& other) {
        if (this == &other) return *this;

        delete[] data;
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) data[i] = other.data[i];

        return *this;
    }

    // Destructor
    ~SensorFrame() {
        delete[] data;
    }

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

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

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

    SensorFrame A(arr);
    SensorFrame B = A;

    B.setIndex3();

    A.print();
    B.print();

    return 0;
}

Explanation & Logic Summary:

The issue occurs because copying a SensorFrame only copies the pointer to the internal buffer, not the buffer itself. This causes multiple objects to share the same memory, leading to unintended data corruption and unsafe destruction behavior.

By implementing a deep-copy constructor, deep-copy assignment operator, and a destructor, each SensorFrame instance fully owns its memory. This ensures isolation, deterministic behavior, and safe memory management.

Firmware Relevance & Real-World Context:

Incorrect copying of telemetry frames, DMA snapshots, or protocol buffers is a common source of embedded field failures. This problem directly reinforces safe ownership, copy semantics, and memory lifetime management—core skills for reliable firmware development.

 

 

 

 

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