ProblemsMemory ManagementFix the destructor
NoviceMemory Management

Fix the destructor

Context

A junior hired because he's your team lead's cousin wrote the Buffer class, approved his own code review and left for a no-signal vacation. On Friday night prod started crashing on every buffer copy, and your team lead 'believes in you'. The double free believes in no one. Fix the class — the vacation has two more weeks to go.

Task

You have a Buffer class that wraps a heap-allocated array. Your colleague wrote it but it has critical bugs — using it crashes or corrupts memory. Implement the full class following the Rule of Three.

Constraints

  • Must not use smart pointers
  • Must follow Rule of Three (destructor + copy constructor + copy assignment)
  • No memory leaks
  • Self-assignment must be handled correctly

Before you code

  • What happens when you copy an object with a raw pointer member using the compiler-generated copy constructor?
  • What is a double-free, and when does it happen?
  • How do you handle self-assignment in operator=?

Tests

  • #1Copy constructor creates independent copy
  • #2Self-assignment does not corrupt
  • #3No double-free on reassignment

Hints

Hint 1

The compiler-generated copy constructor copies the pointer, not the data — so two buffers share one allocation.

Hint 2

In the copy constructor and copy assignment, allocate a NEW array and memcpy the bytes into it.

Hint 3

Guard operator= against self-assignment (if (this == &other) return *this;) before deleting your old buffer.

Editorfix-the-destructor.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.