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
nextpointer step by step to expose silent truncation and memory leaks, provide the fixedinsertAfterimplementation (explaining why assignment ordering matters), and address edge cases (nullptrarguments, 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
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
Nodeas[val | next]. Inside the buggyinsertAfter(prev, val),new Node(val)allocates[val | null]andprev->next = created;redirectsprevto the new node without savingprev's existingnextpointer 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 orphanedNow trace
dumpList(head)iteration by iteration: -pstarts at node10:p->nextis non-null (node20), so it prints"10 -> ". -padvances to node20:p->nextis non-null (node30), so it prints"20 -> ". -padvances to node30:p->nextisnullptr, 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 -> 30Notice why this defect is deceptive: every dereferenced pointer is valid (
nullptrterminates node30cleanly), so the binary never segfaults — it silently drops data.Exercise 1: heap memory leaks and the two-step pointer splice
Omitting
created->next = prev->next;causes two distinct failures:- Silent list truncation: Every node that used to follow
previs detached from the list. Here node40disappears; in a million-node list, inserting right afterheadsevers the entire suffix at once. - Memory leaks: A memory leak happens when heap memory allocated via
newloses its last reachable pointer without being released viadelete.mainactually leaks memory in two ways:- Immediate orphan leak: During
insertAfter(head, 20), overwritinghead->nextdestroys the sole pointer to node40. Even ifmainfreed the list before returning, node40could never be reached (on 64-bit targets, eachNodeoccupies 16 bytes — 4-byteint+ 4 bytes alignment padding + 8-byte pointer — plus allocator bookkeeping). - Missing exit cleanup:
mainnever callsdeleteon the remaining reachable nodes (10,20,30) either.
- Immediate orphan leak: During
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
mainwith the fix builds10 -> 40, then10 -> 20 -> 40, then10 -> 20 -> 30 -> 40, printing10 -> 20 -> 30 -> 40. Allocating withnewbefore mutatingprev->nextalso gives strong exception safety: ifnewthrowsstd::bad_alloc, the original list remains untouched.- Silent list truncation: Every node that used to follow
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, preferassert(prev != nullptr), returning abool, or accepting a referenceinsertAfter(Node& prev, int val)when null should be unrepresentable.- Appending after the tail (
prev->next == nullptr): Step 1 assignscreated->next = nullptrand Step 2 assignsprev->next = created, promotingcreatedto the new tail without any special-case branch. - Inserting before
head(or into an empty list):insertAfterrequires 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 dedicatedpushFront(Node*& head, int val)helper. - Releasing the list safely: Reading
cur->nextafterdelete curis a use-after-free bug (accessing memory already returned to the heap allocator, invoking undefined behavior). Savenextinto a local variable prior todelete:
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 rawnew/delete(if you implement a custom list withstd::unique_ptr<Node> next, write an iterative destructor loop so destroying a deep list cannot overflow the call stack).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
virtualwhose target implementation is resolved at run time via a vtable (a compiler-generated per-class table of function pointers, referenced by a hiddenvptrstored 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 inDerivedperforms 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 standaloneBasevariable holding only theBasesubobject — known as object slicing — soobjhas dynamic typeBase.# 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 -- Static type: The compile-time type of the variable or expression written in source code (
Exercise 2: trace lines 1 through 6 (constructors, name hiding, and default arguments)
Walk through
mainone statement at a time:Derived item;produces lines 1 and 2. C++ initializes class hierarchies base-first:Base()completes beforeDerived's subobjects begin construction. - Line 1 (Base::ping): WhileBase()executes,Derivedhas not started constructing yet — dispatching intoDerived::ping()could touch uninitializedDerivedmembers! C++ setsitem'svptrtoBase's vtable duringBase(), soping()runsBase::ping. - Line 2 (Derived::ping): OnceBase()returns, C++ switchesitem'svptrtoDerived's vtable and entersDerived(), soping()runsDerived::ping. (Destruction runs in reverse —~Derived()then~Base()— and prints nothing here.)Base* ptr = &item;aliases the liveDerivedinstance through aBase*, producing lines 3 through 6: - Line 3 (Derived::ping):pingisvirtualand invoked via pointerptr, so runtime vtable lookup dispatches toDerived::ping. - Line 4 (Base::tag):tagis not declaredvirtualinBase.Derived::tagmerely hidesBase::tagonDerivedexpressions, so calling through static typeBase*binds statically toBase::tag. - Line 5 (Derived::report 10):reportisvirtual, so vtable dispatch selectsDerived::reportat run time — however, the caller omitted the argument inptr->report()! At compile time, the compiler sees static typeBase*, looks upBase::report(int level = 10), and passes10intoDerived::report, printingDerived::report 10. - Line 6 (Derived::report 50): Initem.report(), the static type isDerived, so the compiler substitutesDerived's defaultlevel = 50and runsDerived::report, printingDerived::report 50.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 objis passed by value, so C++ initializesobjwithBase's implicitly generated copy constructorBase(const Base&). - Watch the subtle constructor trap:
Base(const Base&)copies theBasesubobject directly without running the default constructorBase() { ping(); }, so creatingobjprints nothing! - Because
objis now a plainBaseobject (itsDerivedhalf was sliced away and itsvptrpoints toBase's vtable), Line 7 (obj.ping()) printsBase::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- Parameter
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: Writingvoid tag() const overrideinsideDerivedtriggers an immediate compile error becauseBase::tagis notvirtual, catching accidental name hiding or signature mismatches right away. (Usefinalwhen subclasses must not override further, which also permits devirtualization when the static type isDerived.) - Pass polymorphic objects by reference or pointer (
const Base&), and disable slicing: Mark copy/move constructors and assignment operatorsprotectedor= deleteon polymorphic base classes (C++ Core Guidelines C.67) so accidental value copies likeinspectByValue(Base obj)fail at compile time. - Keep default arguments off
virtualmethods via the Non-Virtual Interface (NVI) idiom: Expose one public non-virtual method onBaseowning the single default value and forwarding to aprivate virtualhook:
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
virtualmethods inside constructors or destructors when subclass behavior is desired; pass configuration data upward intoBase(...)or run a two-phase factory helper after construction finishes.
- Annotate every overriding virtual method with
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). Forgettingcreated->next = prev->next;severs everything afterprev, immediately orphaning node40in heap memory (a memory leak, meaning allocated heap storage with no remaining pointer to free it), whilemainalso omitsdeletecleanup before exit. - Exercise 1 repair and ordering: Assign
created->next = prev->next;first andprev->next = created;second whileprev->nextstill holds the old successor, producing10 -> 20 -> 30 -> 40. - Exercise 1 safe deallocation: When destroying a linked list, store
Node* next = cur->next;beforedelete 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 isBase; non-virtual methods (tag) and default parameter values (10vs.50) use the static type; and passingDerivedtoBase objby value causes object slicing (initializing a standaloneBasecopy viaBase's copy constructor). - Compile-time safeguards: Mark overrides with
override, pass polymorphic objects by reference (const Base&), declare base copy operationsprotectedor= delete, and own default arguments on a non-virtual wrapper (Non-Virtual Interface idiom).
Common mistakes
- Reading
main's comments instead of tracingprev->nextand predicting10 -> 20 -> 30 -> 40for the buggy Exercise 1 code, or predicting a segmentation fault when10 -> 20 -> 30 -> nullptris completely well-formed. - Swapping the two pointer assignments in the fix (
prev->next = created; created->next = prev->next;), which wirescreated->nextback ontocreateditself and forms an infinite loop! - Writing
delete cur; cur = cur->next;during cleanup, dereferencing freed memory on every node. - Predicting
Derived::pingon Line 1 (forgetting that unlike Java, C++ keeps the object's dynamic type asBaseinsideBase()so uninitializedDerivedfields are never accessed). - Predicting
Derived::tagforptr->tag()(overlooking the missingvirtualkeyword onBase::tag, which makesDerived::taghide rather than overrideBase::tag). - Predicting
Derived::report 50forptr->report()(forgetting that C++ default arguments come from static typeBase*at compile time, not from the vtable). - Adding a spurious constructor print during
inspectByValue(item)(forgetting that pass-by-value callsBase's copy constructorBase(const Base&), notBase()), or predictingDerived::pingafterobjwas sliced down toBase.
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 overwritesprev->nextwithcreated, so the second linecreated->next = prev->next;setscreated->next = created— creating a self-cycle where the new node points to itself while still leaking the old tail! Tracingmainwith that mistake:insertAfter(head, 40)setsn40->next = n40,insertAfter(head, 20)overwriteshead->nextwithn20(n20->next = n20, leakingn40), andinsertAfter(head->next, 30)setsn20->next = n30withn30->next = n30, causingdumpList(head)to spin endlessly printing10 -> 20 -> 30 -> 30 -> 30 -> .... - In Exercise 2, what happens if
Base::pingbecomes pure virtual (= 0) whileBase()still invokesping()? First, in this exact program, declaringvirtual void ping() const = 0;turnsBaseinto an abstract class (a type that cannot be instantiated by value), sovoid inspectByValue(Base obj)immediately fails to compile because parameters cannot have abstract value type. Even ifinspectByValuetookconst Base&, making an unqualified virtual callping()insideBase()to a pure virtual method ofBaseis undefined behavior in C++: compilers warn and either fail at link time (looking for a missingBase::pingbody) or abort at run time (Pure virtual function called!). - What does the compiler do if you mark
Derived::tagwithoverridewithout changingBase? The compiler rejects the program immediately with a diagnostic stating thatDerived::tagis markedoverridebut does not override anyvirtualmember function inBase. Surfacing accidental name hiding or signature mismatches as hard compile errors is the exact purpose of C++11override; addingvirtualtoBase::tagfixes the error and makesptr->tag()printDerived::tag. - How should
inspectByValuebe modified so that callingping()inside it runsDerived::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 slicingitem, soobjaliases the liveDerivedinstance andobj.ping()dispatches throughDerived's vtable to printDerived::pingon Line 7. To stop callers elsewhere from slicingBaseaccidentally, also markBase's copy constructor and copy-assignment operatorprotectedor= delete.
Follow-up questions
- In Exercise 1, what happens at runtime if your fix writes the two pointer assignments in reverse order?
- In Exercise 2, what happens if `Base::ping` becomes pure virtual (`= 0`) while `Base()` still invokes `ping()`?
- What does the compiler do if you mark `Derived::tag` with `override` without changing `Base`?
- How should `inspectByValue` be modified so that calling `ping()` inside it runs `Derived::ping`?
Similar questions
- Verifying an RTL Block with a SystemVerilog UVM Testbench
- Constant-Time Fixed-Capacity LRU Cache
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs
- Cache-Set Conflicts, False Sharing, and GPU Bank Serialization
- GPU Kernel Register Spilling, Occupancy Trade-Offs, and Performance Diagnosis
- Agent Skill Packaging and Progressive Context Disclosure
More AMD interview questions
- Verifying an RTL Block with a SystemVerilog UVM Testbench Easy
- Top K Elements via Partition Selection Medium
- Single-Agent Versus Multi-Agent Orchestration Architectures Medium Pro
- Constant-Time Fixed-Capacity LRU Cache Medium Pro
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs Medium Pro
- Validation Architecture for Kernel and Compiler Optimization Agents Medium Pro
- Cache-Set Conflicts, False Sharing, and GPU Bank Serialization Medium Pro
- GPU Kernel Register Spilling, Occupancy Trade-Offs, and Performance Diagnosis Medium Pro
- Mastering and Validating Unfamiliar Technologies Medium Pro
- Agent Skill Packaging and Progressive Context Disclosure Medium Pro