0

How deep can a recursive call go before a stackoverflow exception is thrown in c#?

Is this a constant value or machine dependent? I am writing a small application that processes a tree structure recursively and I am scared of getting a stackoverflow exception on some machines.

The three can have 50 levels at most so around 50 recursive calls one after another. Is this much?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Alecu
  • 2,627
  • 3
  • 28
  • 51
  • I haven't ever got such an error with a proper code; only with infinite loops or similar. – varocarbas Nov 16 '15 at 12:05
  • Impossible to say. Stack size can be changed, Default is different in different contexts (desktop app, ASP.NET 32/64 bit) and we don't know how much stack each call you (because of stack allocated variables and/or explicit stack allocated arrays with stackalloc). In general should be easier to rewrite such function in a non-recurisve form (a tree iterator is easy to implement with yield without any recursion) – Adriano Repetti Nov 16 '15 at 12:06
  • depends on amout of parameters and their type. From lessons learned - if you recursion nested level more than 10 - its time to look for another implementation – Yaugen Vlasau Nov 16 '15 at 12:09
  • Not 50, thousands. Recursive algorithms should never be worse than O(logN). Should not be a problem with tree walks unless your tree is hopelessly imbalanced. Which is a bug. – Hans Passant Nov 16 '15 at 12:20

0 Answers0