Linux Stack Sizes

How do I find the maximum stack size?

You can query the maximum process and stack sizes using getrlimit. Stack frames don't have a fixed size; it depends on how much local data (i.e., local variables) each frame needs.

To do this on the command-line, you can use ulimit.

If you want to read these values for a running process, I don't know of any tool that does this, but it's easy enough to query the /proc filesystem:

cat /proc/<pid>/limits

Maximum size of stack of multi threaded process


each thread of a process gets a stack, while there's typically only
one heap for the process.

That's correct.

Is this limit applicable at process level or each thread can have
1MB/8MB stack?

Each thread gets its own stack; the stack-size-limit is per-thread (i.e. it is not a shared limit for all threads in the process)

And what happens to the memory allotted to stack after thread exit?

The memory pages are released and become available for use by other code in the future.

Stack size on Linux - Limited stack size vs automatic stack expansion

The stack can grow, but not indefinitely. As shown in the diagram in the first question you link to, the stack and the heap can both grow into the free memory area, but if they keep growing eventually they'll run into each other.

It's not common to write programs that need an enormous amount of stack growth. Often if a program keeps growing the stack, it's an indicator a bug causing infinite recursion. Limiting the stack size catches these errors. While there are some algorithms that recurse deeply, they're not common, and can often be refactored into iterative algorithms.

The problem with
int a[1000000];
isn't that it "wastes" the stack. Most architectures have a relatively small limit to the size of a single stack frame, so you can't have such large arrays as local variables.

But except for that, the usual reason to choose heap versus stack memory is related to how the data will be used. Variables on the stack are declared statically in the program code. If you need a variable number of objects, it's usually necessary to use the heap (C has variable-length arrays, but C++ doesn't, and you can't resize them like you can with realloc()). Also, memory allocated on the stack goes away when the function returns, so you must use heap objects for data that persists beyond a single function.

Don't worry about what's he's talking about at 47:40 in the video. Application programs just deal with virtual memory, physical memory is totally hidden and only relevant to the internals of the virtual memory subsystem in the kernel.

The process break is used by the runtime library's implementation of malloc(). You don't normally deal with it directly in application programs.



Related Topics



Leave a reply



Submit