KatInterview

Reading C++: Linked List Bug and Polymorphic Dispatch Tracing

BehavioralModel answer
MediumModel answerBehavioralc++code-readingpointers

Last updated

Find the bug in a linked list insertion function and predict the output of a C++ program involving virtual functions, constructors, and slicing.

You are given two short C++ programs to analyze without running them.

Part 1: Debug the Linked List Insertion

The function insertAfter(prev, value) should insert a new node containing value immediately after the node prev. The comments in main describe the intended list after each call.

#include <iostream>

struct Node {
  int value;
  Node* next;
  Node(int v) : value(v), next(nullptr) {}
};

void insertAfter(Node* prev, int value) {
  if (prev == nullptr) return;
  Node* node = new Node(value);
  prev->next = node;
}

void print(const Node* head) {
  for (const Node* cur = head; cur != nullptr; cur = cur->next) {
    std::cout << cur->value << (cur->next ? " -> " : "\n");
  }
}

int main() {
  Node* head = new Node(1);
  insertAfter(head, 3);        // intended: 1 -> 3
  insertAfter(head, 2);        // intended: 1 -> 2 -> 3
  insertAfter(head->next, 4);  // intended: 1 -> 2 -> 4 -> 3
  print(head);
}

Your tasks:

  • Predict the exact output this program produces
  • Identify the bug and explain its consequences
  • Provide a corrected version of insertAfter
  • Discuss edge cases and potential memory issues

Part 2: Trace Polymorphic Behavior

Predict the exact output of this program, line by line. For each line of output, explain which language rule determines what gets printed.

#include <iostream>

class Base {
public:
  Base() { hello(); }
  virtual ~Base() = default;
  virtual void hello() const { std::cout << "Base::hello\n"; }
  void greet() const { std::cout << "Base::greet\n"; }
  virtual void show(int x = 1) const { std::cout << "Base::show " << x << "\n"; }
};

class Derived : public Base {
public:
  Derived() { hello(); }
  void hello() const override { std::cout << "Derived::hello\n"; }
  void greet() const { std::cout << "Derived::greet\n"; }
  void show(int x = 2) const override { std::cout << "Derived::show " << x << "\n"; }
};

void byValue(Base b) { b.hello(); }

int main() {
  Derived d;
  Base* p = &d;
  p->hello();
  p->greet();
  p->show();
  d.show();
  byValue(d);
}

Your tasks:

  • Predict the complete output with exact text
  • Explain the mechanism behind each line printed
  • Identify which language features cause surprising behavior
  • Suggest how to avoid these pitfalls in production code

Hints

Hint 1

In Part 1, trace what each insertAfter call does to the next pointers. What happens to the node created in the first call?

Hint 2

In Part 2, virtual dispatch does not work during base-class construction. The object is not yet a Derived.

Hint 3

When a Derived object is passed by value as a Base parameter, only the Base portion is copied—this is called object slicing.