KatInterview

Spot the Slicing and Double-Free Bugs in a C++ Buffer Hierarchy

Data Structure DesignModel answer
MediumModel answerData Structure Designcppraiirule-of-five

Last 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

  1. 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).
  2. Explain the root cause. Describe how MessageBlock violates the Rule of Three / Five, and walk through exactly what happens during the call dispatch(urgent).
  3. Fix it. Give a corrected version that uses modern C++ (RAII, the Rule of Zero, std::vector or 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.