Reputation: 75
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.
Upvotes: 4
Views: 279
Reputation: 4498
The main reason for a stack overflow error to happen is to have a large count of functions calls, an example that would through this error would be like this:
static int x = 0;
static void Main()
{
fn();
}
static void fn()
{
Console.WriteLine(x++);
fn();
}
This happens due to something wrong at the code, because this usually happens after few thousands of calls.
The application above exited like this:
...
15706
15707
15708
Process is terminated due to StackOverflowException.
You could learn to see the "Call Stack" windows in the debugger, it will display the list of function calls.
Upvotes: 1
Reputation: 67898
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.
Upvotes: 7
Reputation: 700262
Only local variables that are value types are allocated only on the stack. For a reference type like Image
only the reference is allocated on the stack, the object is allocated on the heap.
Upvotes: 4
Reputation: 598765
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.
Upvotes: 6
Reputation: 720
Your local variables are actually references ("pointers"). Those images are not stored on the stack ;)
Upvotes: 2