Justin
Justin

Reputation: 6549

Stackoverflow exception with no noticeable reason

I have a page I test things out on, so this isn't exactly super important to fix, but I would like to know what is causing this exception. The page is very simple. I have a function called MakeTheData that is about 38,000 lines long of adding data points. I noticed when starting the page I was getting a stack overflow exception.

You can see here that it hits the breakpoint to call the function. I then continue....

enter image description here

And now I get a stack overflow exception without even hitting the first breakpoint in the function. How is this even happening?

enter image description here

Upvotes: 0

Views: 157

Answers (2)

Andy Hopper
Andy Hopper

Reputation: 3678

A StackOverflowException can occur for a number of reasons; what the error is really telling you is that the thread ran out of stack space to store local variables. It just so happens that the one we're most familiar with is the classic "recursive call that never unwinds."

By any chance, is your DataPoint a struct? It's possible that it's allocating a local variable for each "new DataPoint" line, which means the size will be the struct size * 38000. Given that you're not going to have that thread's stack to yourself (the stack of the ASP.NET request pipeline will be sitting right on top of your method call), you may not have much space left.

One way (and probably the simplest way) to work around this would be to break your method call into multiple methods; That way the memory allocation would be kept lower and avoid blowing the stack out.

Upvotes: 0

fejesjoco
fejesjoco

Reputation: 11903

Split MakeTheData into multiple parts or try a release build. I think the .NET runtime is trying to allocate space for 38000 local variables (of DataPoint type) when entering the function, and that causes a stack overflow instantly.

Update: plus, as @JonSkeet said, don't make such huge functions at all in the first place. I'm still curious if it is fixed by an optmized build.

Upvotes: 6

Related Questions