Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack overflow in C# application

I am new to the concept of memory division in programming. I have found that size of stack is in most cases in .NET applications 1MB round. My question is: "How doesn't the stack overflow appear when in some functions I use local variables for "Image" type that is bigger than 1MB. Thanks in advance.

like image 915
user1932153 Avatar asked Nov 30 '22 04:11

user1932153


2 Answers

Because a StackOverflow exception has nothing to do with stack or heap memory management. Per the MSDN Documentation:

The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.

Now, if you're talking about the stack as far as the memory is concerned, then we're in a different world. The images you're storing in memory are likely held on the Large Object Heap. Memory management, and the conversation of it, is much too broad for this forum - but if you have a specific question about memory management then we can address that.

It's important that you understand that you are mixing two nomenclatures, and concepts, in your question and that there is an explicit difference between the two. I don't want you to go on thinking that you should be getting a StackOverflow exception because of large objects. I also don't want you to go on thinking that you are getting a StackOverflow exception because of large objects and memory management.

like image 111
Mike Perrenoud Avatar answered Dec 11 '22 11:12

Mike Perrenoud


The image itself is not stored on the stack, it is stored on the heap. Only a pointer/reference to the image is kept on the stack, which is a lot smaller.

public static void DoSomethingToImage()
{
    Image img = new Image(...);
}

In the above code fragment, the Image is allocated on the heap and a reference to the image is stored in the img variable on the stack.

like image 30
Frank van Puffelen Avatar answered Dec 11 '22 12:12

Frank van Puffelen