Recursion and system resources: can too many recursive calls in a C program cause a stack overflow on typical systems?

Difficulty: Easy

Correct Answer: Yes

Explanation:


Introduction / Context:
Every function call consumes stack space for return addresses, saved registers, and local variables. Deep or unbounded recursion can therefore exceed the stack limit. This question verifies awareness of the real risk of stack overflow due to recursion depth.


Given Data / Assumptions:

  • Typical OS-enforced per-thread stack sizes (for example, a few MB on many systems).
  • No tail-call guarantee; each recursive level uses stack.
  • Potentially large local arrays/structures increase stack usage per call.


Concept / Approach:
Stack memory is finite. With each recursive call, new frames are allocated. If recursion depth * frame size exceeds the stack limit, a stack overflow occurs, typically resulting in a crash (segmentation fault) or an OS exception.


Step-by-Step Solution:

Estimate recursion depth (for example, input size N).Estimate per-frame stack usage (locals + call metadata).Compare total usage to the stack limit; if exceeded, overflow occurs.Mitigate by converting to iteration, using heap allocations, or adding guards.


Verification / Alternative check:
Run a deliberately deep recursive function and observe failure at high depths; increase stack size or refactor to iteration to prevent overflow.


Why Other Options Are Wrong:

No: contradicts fundamental finite-stack reality.“Only in debug builds/with long double/only on Windows” are myths; the risk exists across platforms and builds.


Common Pitfalls:
Ignoring worst-case depth; using large VLAs or structs on the stack within recursive functions; forgetting that each thread has its own (often smaller) stack.


Final Answer:
Yes.

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion