Spot the Slicing and Double-Free Bugs in a C++ Buffer Hierarchy
Data Structure DesignModel answerLast updated
Review a C++ class hierarchy that owns a raw heap buffer, explain why passing it by value breaks it, and rewrite it with modern ownership and correct polymorphic dispatch.
Code review: a message-block hierarchy
You are reviewing a C++ module from a messaging component. A base class owns a raw byte buffer, and a derived class adds a priority. The code compiles but misbehaves at runtime.
#include <cstddef>
#include <cstring>
#include <iostream>
class MessageBlock {
public:
explicit MessageBlock(std::size_t n) : len_(n), bytes_(new char[n]) {
std::memset(bytes_, 0, len_);
}
virtual ~MessageBlock() {
delete[] bytes_;
}
virtual void process() const {
std::cout << "Plain block, " << len_ << " bytes\n";
}
protected:
std::size_t len_;
char* bytes_;
};
class UrgentMessageBlock : public MessageBlock {
public:
UrgentMessageBlock(std::size_t n, int level)
: MessageBlock(n), level_(level) {}
void process() const override {
std::cout << "Urgent block (level " << level_ << "), "
<< len_ << " bytes\n";
}
private:
int level_;
};
void dispatch(MessageBlock block) {
block.process();
}
int main() {
UrgentMessageBlock urgent(256, 1);
dispatch(urgent);
return 0;
}
What to answer
- Find the bugs. Explain why this program has undefined behavior (a double free) and why
process()does not do what the author expects (object slicing). - Explain the root cause. Describe how
MessageBlockviolates the Rule of Three / Five, and walk through exactly what happens during the calldispatch(urgent). - Fix it. Give a corrected version that uses modern C++ (RAII, the Rule of Zero,
std::vectoror smart pointers). Change the function signature and the call so that virtual dispatch works, with no slicing and no needless allocation.
Hints
Hint 1
Ask what a by-value parameter of base type does when you pass a derived object. Which constructor runs, and which parts of the argument does it see?
Hint 2
The class has a destructor that frees memory but declares no copy operations. What does the compiler-generated copy do to a raw `char*` member, and how many destructors then run on that address?
Hint 3
Two separate fixes are needed: one for who owns the bytes (replace the raw pointer with a type that manages itself) and one for how the object is passed (a type that keeps the dynamic type). Consider also forbidding copies of the polymorphic base.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
(The original snippet's <cstring> and <iostream> includes are assumed present, as shown.)
What happens in dispatch(urgent)
Three things happen in sequence, and two of them are bugs.
- Slicing.
dispatchtakesMessageBlockby value. Passing anUrgentMessageBlockinvokesMessageBlock's copy constructor, which sees only the base subobject ofurgent.level_is dropped.- The new object is a genuine
MessageBlock, so its vptr refers to the base vtable. block.process()therefore prints "Plain block". Virtual dispatch is not broken. The object simply is no longer an urgent block.
- Shallow copy.
MessageBlockdeclares no copy constructor, so the compiler generates a memberwise one. Copyingbytes_copies the pointer value, not the bytes. Two objects now point at one heap block. - Double free.
- When
dispatchreturns, the parameter's destructor runsdelete[] bytes_. - At the end of
main,urgent's destructor runsdelete[]on the same address. - Freeing the same pointer twice is undefined behavior. It can show up as an allocator abort, silent heap corruption, or an exploitable condition. In between,
urgent.bytes_is dangling.
- When
Root cause: Rule of Three / Five
The class owns a resource and has a destructor that releases it, but it defines no other special member functions.
- Rule of Three: a class that needs a custom destructor almost always needs a custom copy constructor and copy assignment too. The implicit versions are wrong for an owning raw pointer.
- Rule of Five: declaring a destructor suppresses the implicit move operations, so "moves" quietly degrade to the broken copies.
- Copy assignment is worse:
a = bleaksa's old buffer and then leaves two owners ofb's buffer.
A deeper design flaw is that a polymorphic base is copyable by value. That makes slicing easy to trigger and invisible to the compiler.
The fix
Two independent changes are needed.
1. Ownership: use the Rule of Zero. Store the bytes in a std::vector<char>. It deep-copies, moves and frees correctly, so no class needs a hand-written destructor body or copy logic. (std::unique_ptr<char[]> also works if you want move-only ownership.)
2. Polymorphism.
- Take the parameter as
const MessageBlock&. There is no copy and no allocation, and the dynamic type is preserved. - Delete copy and move on the polymorphic base (C++ Core Guidelines C.67), so any future pass-by-value becomes a compile error rather than a silent slice.
- If real duplicates are needed, add a virtual
clone()returningstd::unique_ptr<MessageBlock>.
#include <cstddef>
#include <iostream>
#include <memory>
#include <vector>
class MessageBlock {
public:
explicit MessageBlock(std::size_t n) : bytes_(n) {} // zero-filled
virtual ~MessageBlock() = default; // safe delete via base pointer
MessageBlock(const MessageBlock&) = delete; // no slicing, no aliasing
MessageBlock& operator=(const MessageBlock&) = delete;
MessageBlock(MessageBlock&&) = delete;
MessageBlock& operator=(MessageBlock&&) = delete;
virtual void process() const {
std::cout << "Plain block, " << size() << " bytes\n";
}
std::size_t size() const noexcept { return bytes_.size(); }
private:
std::vector<char> bytes_; // sole owner of the memory
};
class UrgentMessageBlock final : public MessageBlock {
public:
UrgentMessageBlock(std::size_t n, int level)
: MessageBlock(n), level_(level) {}
void process() const override {
std::cout << "Urgent block (level " << level_ << "), "
<< size() << " bytes\n";
}
private:
int level_;
};
void dispatch(const MessageBlock& block) { // reference: no copy, no slice
block.process();
}
int main() {
UrgentMessageBlock urgent(256, 1);
dispatch(urgent); // Urgent block (level 1), 256 bytes
std::unique_ptr<MessageBlock> owned =
std::make_unique<UrgentMessageBlock>(512, 2);
dispatch(*owned); // Urgent block (level 2), 512 bytes
}
Why this is correct
- One owner per buffer. Each vector frees its own storage exactly once.
- No aliasing is possible. The base cannot be copied, so a second object can never share the bytes.
- Dispatch is preserved. A reference keeps the most-derived type, so the call reaches the override.
- Deleting through a base pointer is safe. The destructor is virtual, so
owneddestroys the full derived object. Without that, theunique_ptrdestruction would be UB.
Complexity
- Construction is O(n) time and space, the same as the original
newplusmemset. dispatchis O(1): one reference and one indirect call. A correct deep-copy-by-value version would cost O(n) time and a heap allocation on every call.
Edge cases and common mistakes
- Fixing only the copy. Writing a deep copy constructor removes the double free but leaves slicing, and now pays an O(n) allocation per call.
- Fixing only the signature. Switching to a reference removes the symptom here, but the class is still a trap for any future copy or assignment.
- Forgetting the virtual destructor on a base used through pointers. The original had it right, and the rewrite keeps it.
- Size 0.
std::vector<char>(0)is valid, as wasnew char[0]. - Allocation failure.
std::bad_allocpropagates out of the constructor and nothing leaks, since the object never finished constructing. - Implicit conversions. Keep single-argument constructors
explicit, sodispatch(256)cannot silently build a temporary.
Follow-ups you should be ready for
Copy-and-swap. If you must manage a raw resource, write a proper deep-copy constructor, then define assignment by value:
Buf& operator=(Buf other) noexcept { swap(*this, other); return *this; }
The only operation that can throw is the parameter copy, and it happens before *this is touched, which gives the strong exception guarantee. Self-assignment works automatically, and one function covers both copy and move assignment. The cost is an allocation even when existing capacity could have been reused.
Allocation-free hot paths. For latency-critical code, make capacity a compile-time property (std::array<char, N> or a template parameter), or pre-allocate at startup using object pools, ring buffers or a std::pmr::monotonic_buffer_resource that is reset each cycle. This removes allocator latency and fragmentation from the critical path.
Needing real copies of polymorphic objects. Use a virtual clone() (the "virtual copy constructor" idiom), so duplication is explicit and always preserves the dynamic type.