80. Deep Copy Assignment Buffer

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

class SensorBuffer {
private:
    uint8_t* data;
    int size;

public:
    // Constructor: allocate buffer
    SensorBuffer(int n) : size(n) {
        data = new uint8_t[size];
    }

    // Destructor: free buffer
    ~SensorBuffer() {
        delete[] data;
    }

    // Copy assignment operator: deep copy
    SensorBuffer& operator=(const SensorBuffer& other) {
        if (this == &other) {
            return *this; // Handle self-assignment
        }

        delete[] data;              // Release old memory
        size = other.size;          // Copy size
        data = new uint8_t[size];   // Allocate new buffer

        for (int i = 0; i < size; i++) {
            data[i] = other.data[i];
        }

        return *this;
    }

    void set(int index, uint8_t value) {
        data[index] = value;
    }

    void print() const {
        for (int i = 0; i < size; i++) {
            cout << (int)data[i];
            if (i != size - 1) cout << " ";
        }
    }
};

int main() {
    int N1, N2;

    cin >> N1;
    SensorBuffer A(N1);
    for (int i = 0; i < N1; i++) {
        int temp;
        cin >> temp;
        A.set(i, (uint8_t)temp);
    }

    cin >> N2;
    SensorBuffer B(N2);
    for (int i = 0; i < N2; i++) {
        int temp;
        cin >> temp;
        B.set(i, (uint8_t)temp);
    }

    A = B;

    A.print();
    return 0;
}

Explanation & Logic Summary

This class manages heap-allocated memory, so the copy assignment operator must ensure exclusive ownership.

The correct deep-copy process is:

  1. Check for self-assignment
  2. Release previously allocated memory
  3. Allocate a new buffer matching the source size
  4. Copy every byte from the source buffer

A shallow copy (copying only the pointer) would result in:

  • Multiple objects referencing the same memory
  • Double-free errors during destruction
  • Data corruption and unstable behavior

Deep copying ensures safe and predictable behavior in memory-constrained and safety-critical embedded systems.

Firmware Relevance & Real-World Context

In real embedded and firmware systems, dynamically allocated buffers are often used for:

  • Sensor sample storage
  • ADC or DMA data snapshots
  • Communication packet assembly
  • Variable-length protocol parsing

Incorrect handling of buffer ownership is a frequent source of:

  • Memory corruption
  • Hard faults
  • System resets

This practice problem reinforces correct deep-copy semantics, a critical Embedded C++ skill for building robust and maintainable firmware.

 

 

 

 

Loading...

Input

4 10 20 30 40 4 1 1 1 1

Expected Output

1 1 1 1