Debugging Singly Linked-List Insertion and Tracing C++ Method Dispatch

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Prompt

In this C++ code-reading interview exercise, begin by stating any brief assumptions you would confirm up front (such as targeting standard-conforming C++17, predicting exact stdout spacing and newlines, and pointing out memory leaks or API pitfalls alongside the printed output). Then analyze both standalone programs below.

Exercise 1 — Singly linked-list insertion (insertAfter): insertAfter(prev, val) is meant to splice a newly allocated node holding val immediately after prev. The inline comments in main indicate the sequence the author expected after each call. Identify the bug, predict the exact output printed by dumpList(head), explain what happens in heap memory, and write the corrected function.

#include <iostream>

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

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

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

int main() {
    Node* head = new Node(10);
    insertAfter(head, 40);       // target state: 10 -> 40
    insertAfter(head, 20);       // target state: 10 -> 20 -> 40
    insertAfter(head->next, 30); // target state: 10 -> 20 -> 30 -> 40
    dumpList(head);
}

Exercise 2 — Inheritance, method dispatch, and pass-by-value: Determine the exact lines printed to stdout when this program runs, and explain the language rule behind every single output line.

#include <iostream>

class Base {
public:
    Base() { ping(); }
    virtual ~Base() = default;
    virtual void ping() const { std::cout << "Base::ping\n"; }
    void tag() const { std::cout << "Base::tag\n"; }
    virtual void report(int level = 10) const {
        std::cout << "Base::report " << level << "\n";
    }
};

class Derived : public Base {
public:
    Derived() { ping(); }
    void ping() const override { std::cout << "Derived::ping\n"; }
    void tag() const { std::cout << "Derived::tag\n"; }
    void report(int level = 50) const override {
        std::cout << "Derived::report " << level << "\n";
    }
};

void inspectByValue(Base obj) { obj.ping(); }

int main() {
    Derived item;
    Base* ptr = &item;
    ptr->ping();
    ptr->tag();
    ptr->report();
    item.report();
    inspectByValue(item);
}

Scope & Expectations

  • Exercise 1 trace and repair: State the exact console output, trace every heap node and next pointer step by step to expose silent truncation and memory leaks, provide the fixed insertAfter implementation (explaining why assignment ordering matters), and address edge cases (nullptr arguments, tail insertion, and safe list deallocation).
  • Exercise 2 line-by-line output: Predict every output line in exact order and connect each call to the expression's static type and the object's dynamic type at that instant.
  • Core C++ dispatch rules: Explain virtual dispatch during base/derived construction, non-virtual name hiding, static binding of default parameter values on virtual functions, and object slicing under pass-by-value.
  • Compile-time C++ safeguards: Show how override, final, reference parameters, non-copyable polymorphic bases, and the Non-Virtual Interface (NVI) idiom prevent these traps at compile time.

Step-by-step walkthrough

  1. Exercise 1: trace the pointers box by box

    In a code-reading interview, execute the statements, never the comments — inline comments only record what the author hoped would happen. Draw each heap-allocated Node as [val | next]. Inside the buggy insertAfter(prev, val), new Node(val) allocates [val | null] and prev->next = created; redirects prev to the new node without saving prev's existing next pointer first:

    1) Node* head = new Node(10);
       head --> [10 | null]
    
    2) insertAfter(head, 40);
       head --> [10 | *-]---> [40 | null]
    
    3) insertAfter(head, 20);      // overwrites head->next!
       head --> [10 | *-]---> [20 | null]
                              [40 | null]   <-- orphaned in heap memory (unreachable!)
    
    4) insertAfter(head->next, 30); // prev is head->next, which is node 20
       head --> [10 | *-]---> [20 | *-]---> [30 | null]
                              [40 | null]   <-- still orphaned
    

    Now trace dumpList(head) iteration by iteration: - p starts at node 10: p->next is non-null (node 20), so it prints "10 -> ". - p advances to node 20: p->next is non-null (node 30), so it prints "20 -> ". - p advances to node 30: p->next is nullptr, so it prints "30\n" and exits the loop.

    The program prints one exact line terminated by a newline (no crash, no trailing spaces):

    10 -> 20 -> 30
    

    Notice why this defect is deceptive: every dereferenced pointer is valid (nullptr terminates node 30 cleanly), so the binary never segfaults — it silently drops data.

  2. Exercise 1: heap memory leaks and the two-step pointer splice

    Omitting created->next = prev->next; causes two distinct failures:

    1. Silent list truncation: Every node that used to follow prev is detached from the list. Here node 40 disappears; in a million-node list, inserting right after head severs the entire suffix at once.
    2. Memory leaks: A memory leak happens when heap memory allocated via new loses its last reachable pointer without being released via delete. main actually leaks memory in two ways:
      • Immediate orphan leak: During insertAfter(head, 20), overwriting head->next destroys the sole pointer to node 40. Even if main freed the list before returning, node 40 could never be reached (on 64-bit targets, each Node occupies 16 bytes — 4-byte int + 4 bytes alignment padding + 8-byte pointer — plus allocator bookkeeping).
      • Missing exit cleanup: main never calls delete on the remaining reachable nodes (10, 20, 30) either.

    Picture splicing a person into a chain of people holding hands: the newcomer must grab the next person's hand before the previous person lets go. That makes the order of the two pointer assignments mandatory:

    void insertAfter(Node* prev, int val) {
        if (prev == nullptr) return;
        Node* created = new Node(val);
        created->next = prev->next;  // Step 1: attach new node to old successor FIRST
        prev->next = created;        // Step 2: point prev at new node SECOND
    }
    
    Before:             prev --> [10 | *-]-----------------> [40 | null]
    
    After Step 1:       prev --> [10 | *-]-----------------> [40 | null]
                                             [20 | *-]------^
    
    After Step 2:       prev --> [10 | *-]---> [20 | *-]---> [40 | null]
    

    Re-running main with the fix builds 10 -> 40, then 10 -> 20 -> 40, then 10 -> 20 -> 30 -> 40, printing 10 -> 20 -> 30 -> 40. Allocating with new before mutating prev->next also gives strong exception safety: if new throws std::bad_alloc, the original list remains untouched.

  3. Exercise 1: edge cases and use-after-free-safe cleanup

    Cover four practical corner cases to complete Exercise 1:

    • prev == nullptr: Returning silently can mask caller bugs because nothing is inserted and no error is signaled. Depending on API contract, prefer assert(prev != nullptr), returning a bool, or accepting a reference insertAfter(Node& prev, int val) when null should be unrepresentable.
    • Appending after the tail (prev->next == nullptr): Step 1 assigns created->next = nullptr and Step 2 assigns prev->next = created, promoting created to the new tail without any special-case branch.
    • Inserting before head (or into an empty list): insertAfter requires a valid predecessor node, so inserting a new front element requires either a sentinel (dummy) head node (a permanent placeholder preceding the first data node) or a dedicated pushFront(Node*& head, int val) helper.
    • Releasing the list safely: Reading cur->next after delete cur is a use-after-free bug (accessing memory already returned to the heap allocator, invoking undefined behavior). Save next into a local variable prior to delete:
    void destroyList(Node* head) {
        while (head != nullptr) {
            Node* next = head->next;  // Save successor BEFORE freeing *head
            delete head;
            head = next;
        }
    }
    

    In production C++, std::forward_list<int> manages singly linked nodes automatically without raw new/delete (if you implement a custom list with std::unique_ptr<Node> next, write an iterative destructor loop so destroying a deep list cannot overflow the call stack).

  4. Exercise 2: the three-question checklist for C++ method dispatch

    To predict every line of Exercise 2 systematically, separate three concepts:

    • Static type: The compile-time type of the variable or expression written in source code (Base*, Derived, Base).
    • Dynamic type: The concrete class of the object occupying memory at the exact moment the call executes.
    • Virtual function: A member function declared virtual whose target implementation is resolved at run time via a vtable (a compiler-generated per-class table of function pointers, referenced by a hidden vptr stored inside each polymorphic instance).

    Apply four standard C++ rules across the 7 calls triggered by main: 1. Non-virtual methods ignore the vtable completely and bind at compile time from the static type. Declaring a same-named method in Derived performs name hiding, not overriding. 2. Inside a constructor (or destructor), the object's active dynamic type is the class whose constructor (or destructor) is currently executing — never a more-derived subclass whose fields have not been initialized yet. 3. Default parameter values are substituted at compile time from the call expression's static type, even when the method body itself dispatches virtually at run time! 4. Pass-by-value (Base obj) copy-constructs a standalone Base variable holding only the Base subobject — known as object slicing — so obj has dynamic type Base.

    #  Call site                   Static type  Dynamic type   Virtual?  Body executed    Default arg
    -  --------------------------  -----------  -------------  --------  ---------------  -----------
    1  ping() inside Base()        Base*        Base           yes       Base::ping       -
    2  ping() inside Derived()     Derived*     Derived        yes       Derived::ping    -
    3  ptr->ping()                 Base*        Derived        yes       Derived::ping    -
    4  ptr->tag()                  Base*        Derived        no        Base::tag        -
    5  ptr->report()               Base*        Derived        yes       Derived::report  10 (Base)
    6  item.report()               Derived      Derived        yes       Derived::report  50 (Derived)
    7  obj.ping() in inspectByVal  Base         Base (sliced)  yes       Base::ping       -
    
  5. Exercise 2: trace lines 1 through 6 (constructors, name hiding, and default arguments)

    Walk through main one statement at a time:

    Derived item; produces lines 1 and 2. C++ initializes class hierarchies base-first: Base() completes before Derived's subobjects begin construction. - Line 1 (Base::ping): While Base() executes, Derived has not started constructing yet — dispatching into Derived::ping() could touch uninitialized Derived members! C++ sets item's vptr to Base's vtable during Base(), so ping() runs Base::ping. - Line 2 (Derived::ping): Once Base() returns, C++ switches item's vptr to Derived's vtable and enters Derived(), so ping() runs Derived::ping. (Destruction runs in reverse — ~Derived() then ~Base() — and prints nothing here.)

    Base* ptr = &item; aliases the live Derived instance through a Base*, producing lines 3 through 6: - Line 3 (Derived::ping): ping is virtual and invoked via pointer ptr, so runtime vtable lookup dispatches to Derived::ping. - Line 4 (Base::tag): tag is not declared virtual in Base. Derived::tag merely hides Base::tag on Derived expressions, so calling through static type Base* binds statically to Base::tag. - Line 5 (Derived::report 10): report is virtual, so vtable dispatch selects Derived::report at run time — however, the caller omitted the argument in ptr->report()! At compile time, the compiler sees static type Base*, looks up Base::report(int level = 10), and passes 10 into Derived::report, printing Derived::report 10. - Line 6 (Derived::report 50): In item.report(), the static type is Derived, so the compiler substitutes Derived's default level = 50 and runs Derived::report, printing Derived::report 50.

  6. Exercise 2: trace line 7 (object slicing) and assemble the 7-line output

    Now trace inspectByValue(item);:

    Original variable item (Derived):   Copied parameter obj (Base):
    +---------------------------+       +---------------------------+
    | Base subobject            |  -->  | Base subobject            |
    | (vptr -> Derived vtable)  |       | (vptr -> Base vtable)     |
    +---------------------------+       +---------------------------+
    | Derived subobject         |
    | (sliced away on copy)     |
    +---------------------------+
    
    • Parameter Base obj is passed by value, so C++ initializes obj with Base's implicitly generated copy constructor Base(const Base&).
    • Watch the subtle constructor trap: Base(const Base&) copies the Base subobject directly without running the default constructor Base() { ping(); }, so creating obj prints nothing!
    • Because obj is now a plain Base object (its Derived half was sliced away and its vptr points to Base's vtable), Line 7 (obj.ping()) prints Base::ping.

    Combining all 7 calls yields the exact console output:

    Base::ping
    Derived::ping
    Derived::ping
    Base::tag
    Derived::report 10
    Derived::report 50
    Base::ping
    
  7. Compile-time C++ idioms that prevent Exercise 2's pitfalls

    Modern C++ lets the compiler reject every bug pattern shown in Exercise 2 before the program ever runs:

    • Annotate every overriding virtual method with override: Writing void tag() const override inside Derived triggers an immediate compile error because Base::tag is not virtual, catching accidental name hiding or signature mismatches right away. (Use final when subclasses must not override further, which also permits devirtualization when the static type is Derived.)
    • Pass polymorphic objects by reference or pointer (const Base&), and disable slicing: Mark copy/move constructors and assignment operators protected or = delete on polymorphic base classes (C++ Core Guidelines C.67) so accidental value copies like inspectByValue(Base obj) fail at compile time.
    • Keep default arguments off virtual methods via the Non-Virtual Interface (NVI) idiom: Expose one public non-virtual method on Base owning the single default value and forwarding to a private virtual hook:
    class Base {
    public:
        virtual ~Base() = default;
        // Single public non-virtual entry point owns the default parameter:
        void report(int level = 10) const { doReport(level); }
    
    private:
        virtual void doReport(int level) const {
            std::cout << "Base::report " << level << "\n";
        }
    };
    
    • Avoid calling virtual methods inside constructors or destructors when subclass behavior is desired; pass configuration data upward into Base(...) or run a two-phase factory helper after construction finishes.

Intuition & how it works

Think of Exercise 1's singly linked list like a daisy chain of paperclips where each clip hooks only onto the clip immediately behind it. To splice clip 20 between clip 10 and clip 40, clip 20 must hook onto clip 40 before clip 10 unhooks from 40 to grab 20 — otherwise clip 40 (and anything attached behind it) drops onto the floor and vanishes. For Exercise 2's C++ dispatch rules, think of each method call as dividing work between compile time and run time: the compiler inspects the variable's written declaration (static type) to bind non-virtual functions and fill in default argument constants, whereas the running binary follows a hidden table pointer inside the object (vptr -> vtable) to select virtual method bodies matching the concrete class alive at that exact moment.

Skimming C++ snippets casually goes wrong because readers trust intent rather than mechanics. In Exercise 1, reading the inline comments fools candidates into answering 10 -> 20 -> 30 -> 40 or guessing a null-pointer crash, when the program actually drops node 40 cleanly without crashing. In Exercise 2, assuming "methods in Derived always replace Base" overlooks four strict C++ rules: constructors execute before subclass members exist, non-virtual declarations hide rather than override, default arguments bind statically, and pass-by-value slices off subclass state.

Walk through one miniature trace from each exercise to see the rules in action: - Exercise 1 (insertAfter(head, 40) followed by insertAfter(head, 20)): After the first call, head (10) points to 40. On the second call, prev->next = created overwrites head->next with [20 | null] without ever setting created->next to node 40, leaving 10 -> 20 and leaking node 40 on the heap. - Exercise 2 (Base* ptr = &item; ptr->report();): Because ptr has static type Base*, the compiler stamps in Base's default level = 10, compiling the call as ptr->report(10). At run time, report is virtual and *ptr is a Derived instance, so Derived::report(10) executes and prints Derived::report 10.

Key points

  • Exercise 1 exact output: 10 -> 20 -> 30 (single line). Forgetting created->next = prev->next; severs everything after prev, immediately orphaning node 40 in heap memory (a memory leak, meaning allocated heap storage with no remaining pointer to free it), while main also omits delete cleanup before exit.
  • Exercise 1 repair and ordering: Assign created->next = prev->next; first and prev->next = created; second while prev->next still holds the old successor, producing 10 -> 20 -> 30 -> 40.
  • Exercise 1 safe deallocation: When destroying a linked list, store Node* next = cur->next; before delete cur; to prevent use-after-free (reading freed heap memory, which causes undefined behavior).
  • Exercise 2 exact 7-line output: text Base::ping Derived::ping Derived::ping Base::tag Derived::report 10 Derived::report 50 Base::ping
  • Exercise 2 dispatch summary: Virtual calls via pointers or references use the dynamic type; while Base() runs, the dynamic type is Base; non-virtual methods (tag) and default parameter values (10 vs. 50) use the static type; and passing Derived to Base obj by value causes object slicing (initializing a standalone Base copy via Base's copy constructor).
  • Compile-time safeguards: Mark overrides with override, pass polymorphic objects by reference (const Base&), declare base copy operations protected or = delete, and own default arguments on a non-virtual wrapper (Non-Virtual Interface idiom).

Common mistakes

  • Reading main's comments instead of tracing prev->next and predicting 10 -> 20 -> 30 -> 40 for the buggy Exercise 1 code, or predicting a segmentation fault when 10 -> 20 -> 30 -> nullptr is completely well-formed.
  • Swapping the two pointer assignments in the fix (prev->next = created; created->next = prev->next;), which wires created->next back onto created itself and forms an infinite loop!
  • Writing delete cur; cur = cur->next; during cleanup, dereferencing freed memory on every node.
  • Predicting Derived::ping on Line 1 (forgetting that unlike Java, C++ keeps the object's dynamic type as Base inside Base() so uninitialized Derived fields are never accessed).
  • Predicting Derived::tag for ptr->tag() (overlooking the missing virtual keyword on Base::tag, which makes Derived::tag hide rather than override Base::tag).
  • Predicting Derived::report 50 for ptr->report() (forgetting that C++ default arguments come from static type Base* at compile time, not from the vtable).
  • Adding a spurious constructor print during inspectByValue(item) (forgetting that pass-by-value calls Base's copy constructor Base(const Base&), not Base()), or predicting Derived::ping after obj was sliced down to Base.

Follow-up questions

  • In Exercise 1, what happens at runtime if your fix writes the two pointer assignments in reverse order? Executing prev->next = created; first overwrites prev->next with created, so the second line created->next = prev->next; sets created->next = created — creating a self-cycle where the new node points to itself while still leaking the old tail! Tracing main with that mistake: insertAfter(head, 40) sets n40->next = n40, insertAfter(head, 20) overwrites head->next with n20 (n20->next = n20, leaking n40), and insertAfter(head->next, 30) sets n20->next = n30 with n30->next = n30, causing dumpList(head) to spin endlessly printing 10 -> 20 -> 30 -> 30 -> 30 -> ....
  • In Exercise 2, what happens if Base::ping becomes pure virtual (= 0) while Base() still invokes ping()? First, in this exact program, declaring virtual void ping() const = 0; turns Base into an abstract class (a type that cannot be instantiated by value), so void inspectByValue(Base obj) immediately fails to compile because parameters cannot have abstract value type. Even if inspectByValue took const Base&, making an unqualified virtual call ping() inside Base() to a pure virtual method of Base is undefined behavior in C++: compilers warn and either fail at link time (looking for a missing Base::ping body) or abort at run time (Pure virtual function called!).
  • What does the compiler do if you mark Derived::tag with override without changing Base? The compiler rejects the program immediately with a diagnostic stating that Derived::tag is marked override but does not override any virtual member function in Base. Surfacing accidental name hiding or signature mismatches as hard compile errors is the exact purpose of C++11 override; adding virtual to Base::tag fixes the error and makes ptr->tag() print Derived::tag.
  • How should inspectByValue be modified so that calling ping() inside it runs Derived::ping? Change the parameter from pass-by-value to pass-by-const-reference (or pointer): void inspectByValue(const Base& obj) { obj.ping(); }. Passing by reference avoids copying or slicing item, so obj aliases the live Derived instance and obj.ping() dispatches through Derived's vtable to print Derived::ping on Line 7. To stop callers elsewhere from slicing Base accidentally, also mark Base's copy constructor and copy-assignment operator protected or = delete.

Follow-up questions

Similar questions

More AMD interview questions

All 19 AMD questions →