Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is stack memory size so limited?

When you allocate memory on the heap, the only limit is free RAM (or virtual memory). It makes Gb of memory.

So why is stack size so limited (around 1 Mb) ? What technical reason prevents you to create really big objects on the stack ?

Update : My intent might not be clear, I do not want to allocate huge objects on the stack and I do not need a bigger stack. This question is just pure curiosity.

like image 554
undu Avatar asked May 07 '12 13:05

undu


People also ask

Is stack memory limited?

Yes, stack is always limited. In several languages/compilers you can set the requested size.

What is the size of the stack memory?

Stacks are temporary memory address spaces used to hold arguments and automatic variables during invocation of a subprogram or function reference. In general, the default main stack size is 8 megabytes.

What decides the size of stack memory?

The stack size might increase because: Each register push takes 4 bytes of memory in ARM, while in 16-bit or 8-bit each register push take 2 bytes or 1 byte. In ARM programming, local variables are often stored in the stack, while in some architectures local variables might be defined in a separate data memory area.

How much memory can be allocated on the stack?

On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways.


1 Answers

My intuition is the following. The stack is not as easy to manage as the heap. The stack need to be stored in continuous memory locations. This means that you cannot randomly allocate the stack as needed, but you need to at least reserve virtual addresses for that purpose. The larger the size of the reserved virtual address space, the fewer threads you can create.

For example, a 32-bit application generally has a virtual address space of 2GB. This means that if the stack size is 2MB (as default in pthreads), then you can create a maximum of 1024 threads. This can be small for applications such as web servers. Increasing the stack size to, say, 100MB (i.e., you reserve 100MB, but do not necessarily allocated 100MB to the stack immediately), would limit the number of threads to about 20, which can be limiting even for simple GUI applications.

A interesting question is, why do we still have this limit on 64-bit platforms. I do not know the answer, but I assume that people are already used to some "stack best practices": be careful to allocate huge objects on the heap and, if needed, manually increase the stack size. Therefore, nobody found it useful to add "huge" stack support on 64-bit platforms.

like image 165
user1202136 Avatar answered Sep 18 '22 10:09

user1202136