Understanding stack and heap memory
One of the most common issues with programming is managing memory. To troubleshoot memory issues, you need to start with a deep understanding of how memory is used in .NET projects.
There are two categories of memory: stack memory and heap memory. Stack memory is faster to work with but limited in size. It is fast because it is managed directly by the CPU and it uses a last-in, first-out mechanism, so it is more likely to have data in its L1 or L2 cache. Heap memory is slower but much more plentiful.
On Windows, for ARM64, x86, and x64 machines, the default stack size is 1 MB. It is 8 MB on a typical modern Linux-based operating system. For example, in a macOS or Linux Terminal, I can enter the command ulimit -a
to discover that the stack size is limited to 8,192 KB and that other memory is “unlimited.” This limited amount of stack memory is why it is so easy to fill it up and get a “stack overflow.”
Which...