79. Deep Copy Constructor

You are implementing a sensor packet class that owns dynamically allocated memory.
The class manages a fixed-size buffer of exactly 8 bytes stored on the heap.

Your goal is to correctly implement resource ownership using:

  • A constructor
  • A deep copy constructor
  • A destructor

This problem is designed to verify correct handling of dynamic memory in Embedded C++, where improper copy behavior can cause double-free, memory corruption, or silent data errors.

Class Design:

Private:

  • uint8_t* data;
    Dynamically allocated array of size 8

Public operations:

  • Constructor taking an input array uint8_t arr[8]
  • Copy constructor: SensorData(const SensorData& other)
  • Destructor: ~SensorData()
  • void setIndex3()
    Sets data[3] = 99
  • void print() const
    Prints all 8 bytes separated by spaces

Program Flow:

  1. Read 8 integer values from input
  2. Construct object a using those values
  3. Copy object a into object b using copy initialization
  4. Modify b by calling setIndex3()
  5. Print a, then print b

Correct Behavior:

  • Object a must retain the original data
  • Object b must show the modified value at index 3
  • Each object must own its own independent buffer
  • Program must run with no memory errors

 

Example Input:

1 2 3 4 5 6 7 8 

Example Output:

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

 

Constraints:

  • Exactly 8 input values
  • Each input value is guaranteed to be in the range 0–255
  • Memory must be allocated using new uint8_t[8]
  • Copy constructor must:
    • Allocate a new buffer
    • Copy all 8 bytes from the source object
  • Destructor must release memory using delete[]
  • Objects must not share the same data pointer
  • Output format must match exactly

 

 

 

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