In C++ it's actually possible to throw an exception by value without allocating memory on a heap, so this situation makes sense. But in .NET framework OutOfMemoryException
is a reference type, therefore it is allocated on a heap.
How does .NET framework allocates memory for OutOfMemoryException
when there is not enough memory to create a new object?
|
|||||||||
|
It is preallocated by the runtime. If you explore the heap of any managed process you'll find an instance of that exception. Here are the preallocated exceptions of a Hello World app:
|
|||||||||||||||||||||
|
When an out-of-memory condition is encountered inside the runtime, it calls ThrowOutOfMemory. This calls Exception::GetOOMException, which constructs the object on the stack and then copies it to a statically-allocated global instance, which is then thrown. This is not the managed Exception, though, it a C++ exception declared in ex.h. C++ Exceptions are converted to managed Exceptions in clrex.cpp, which contains code to specifically throw the preallocated managed OutOfMemoryException, which was originally allocated and constructed in appdomain.cpp. Note: Some of these source files are large and may hang your browser for several seconds while it loads the syntax highlighting. The call sites that Tim Schmelter linked in a comment on the other answer aren't related to the runtime running out of memory and being unable to construct an object. |
||||
|