ProgrammingHard
A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A. Use the same recursion with a larger int variable for depth
- B. Recurse but call memset on the stack before each call
- C. Use an explicit stack in a loop, so the depth is limited by heap memory
- 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
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?
- A loop reads n numbers and stores them in int a[n] as a VLA of size up to 10^6 inside main. What is the main risk?
- To sort 10^6 integers with qsort, which comparator is correct for all int values?