views:

480

answers:

2

I got an OutOfMemoryException earlier and couldn't figure out what it was for. It made no sense at all. Dug around in my code, and suddenly remembered that somewhere had forgotten to check for null, and in this particular case it was (and should be) exactly that. That shouldn't cause an OutOfMemoryException in my opinion, but I fixed it anywas of course. And when I did, the exception didn't appear anymore!

So I removed the check again and studied the exception I got some more. And turns out it had an InnerException of type NullReferenceException and a stack trace which of course made a lot more sense.

But why did I get an OutOfMemoryException? This has never happend to me before... makes no sense to me...


Would love to give some more context, but can't really say much without having to upload the whole project, which I can't (And which you wouldn't want to read through anyways :p). But the specific place it happend looks like this:

            {
                foreach (var exportParameter in exportParameters)
                {
                    // Copy to local
                    var ep = exportParameter;

                    // Load stored values from db
                    ...
                }

                int i = 1;
                exportParameters
                    .OrderBy(ø => ø.Sequence)
                    .ForEach(ø => { if (!ø.Locked) ø.Sequence = i++; });
            }

The fix was to put an if(exportParameters != null) before the code block. exportParameters is a List<ExportParameter>, except in the failing case in which it was null.

+1  A: 

Aside from the obvious reason for getting an OOMException, you can also get it if you still have memory available, just not a big enough chunk for what is being requested. If you're getting it reliably and relatively near startup, you're probably accidentally requesting more memory than you intend to (ie. requesting a very large array). Can you post a bit of your code or at least describe your allocation pattern?

Jonathan
A: 

You might be facing the problem that Constrained Execution Regions are designed to prevent - that is, the JITting of some code that your catch clause relies on is causing the out of memory condition.

(In response to svish's comment, this is the first link when googling the phrase: http://msdn.microsoft.com/en-us/library/ms228973.aspx)

Damien_The_Unbeliever
Constrained Execution Regions?
Svish