Katkat

Explain C++ containers, segfaults, and virtual dispatch

TikTokSoftware Engineer · Technical Screen

Last updated

This question assesses the candidate's deep understanding of C++ memory management, the runtime implementation of polymorphism, and the performance characteristics of standard containers.

Part 1: Container Mechanics

You have a large collection of objects that require frequent random access and occasional insertions at the middle of the container. Which standard C++ container would you choose to minimize performance overhead? Explain your reasoning in terms of memory layout and cache locality.

Part 2: Segmentation Faults

Describe three common scenarios in modern C++ development that lead to segmentation faults. Specifically, discuss how the move semantics introduced in C++11 might inadvertently cause a crash if implemented or used incorrectly.

Part 3: Virtual Dispatch

Consider a base class Shape with a virtual void draw() method and a derived class Circle that overrides it.

  1. How does the compiler implement this draw() call at runtime? Explain the role of the vptr and the vtable.
  2. What is the memory overhead of this mechanism for an object instance?
  3. What happens if you call draw() from the Shape constructor or destructor? Why is this discouraged?

Hints

Hint 1

Consider the difference between contiguous memory storage in std::vector and the node-based structure of std::list or std::deque.

Hint 2

Think about memory safety issues involving pointers, such as dangling pointers, double-frees, or invalid iterator invalidation.

Hint 3

Visualize the vptr as an additional hidden pointer field added to every object of a class with at least one virtual function.

Follow-up questions

  • How does the overhead of virtual functions affect the CPU branch predictor, and when would you use the 'curiously recurring template pattern' (CRTP) to avoid it?
  • If you have a base class with a virtual destructor and a derived class that manages a raw memory buffer, what risks arise during object destruction?
  • How would you detect memory leaks or illegal memory access in a large-scale C++ application during the CI/CD pipeline?