ProgrammingHard

A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?

  1. A. Use the same recursion with a larger int variable for depth
  2. B. Recurse but call memset on the stack before each call
  3. C. Use an explicit stack in a loop, so the depth is limited by heap memory
  4. D. Use recursion with malloc for each frame, which is slower and no safer

Correct answer: C. Use an explicit stack in a loop, so the depth is limited by heap memory

Deep recursion can overflow the call stack. An explicit stack on the heap handles the same depth safely and is about as fast.

More C Programming questions

Exams that ask this topic