SensorFrame Deep Copy Fix

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

class SensorFrame {
private:
    uint8_t* data;

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

    // Investigate why copying this object causes corruption,
    // and modify the class implementation so copies do not interfere.
    SensorFrame (const SensorFrame& sb){
        data = new uint8_t[8];
        for (int i=0; i<8; i++){
            data[i] = sb.data[i];
        }
    }
    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;   // This operation exposes the defect

    B.setIndex3();

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

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
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