Will the C program stack shrink?

I noticed that every running C program has a personal mapping to the name [stack], which is initially quite small (128k on my machine), but will grow to accommodate any automatic variables (up to the stack size limit). I assume that here is the call stack of my program.

However, it seems that it never shrinks to its original size. Is there a way to free this memory without interrupting the process?

How is the internal stack C implemented; what increases the size of the display [stack] on demand? Some code generated by the compiler, C-library or operating system? Where does the increase work?

Update: I am using Linux 3.0.0, gcc 4.6.1 and glibc6 on x86-64; since this is probably a pretty concrete implementation, any information on how it works there will be great.

+4
source share
3 answers

In Linux / MMU (in! MMU you cannot grow a stack), the stack grew in a page error handler. For x86, whether to grow the stack is determined by the following code from arch/x86/mm/fault.c:do_page_fault() :

  if (error_code & PF_USER) { /* * Accessing the stack below %sp is always a bug. * The large cushion allows instructions like enter * and pusha to work. ("enter $65535, $31" pushes * 32 pointers and then decrements %sp by 65535.) */ if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) { bad_area(regs, error_code, address); return; } } if (unlikely(expand_stack(vma, address))) { bad_area(regs, error_code, address); return; } 

expand_stack() checks the usual RLIMITS (RLIMIT_AS, RLIMIT_STACK, RLIMIT_MEMLOCK), whether LSM will allow to grow the stack, whether to recompile too much, etc., and finally increase the stack.

+1
source

This is a specific implementation, but I know that the commonly used platform is not used, which reduces the allocated memory stack. Typically, stacks grow on demand, but after the space is locked, it remains locked.

+6
source

I believe that the Linux kernel increases the stack segment (only for the main thread). This is not in the compiler (except for increasing the stack pointer on calls and ignoring the experimental -fsplit-stack option of recent GCC), and not in libC.

If you are sure that your stack has become too large and you do not need it, you may munmap unused part (but be careful: kernel developers do not think about it, so they may not work as expected, in the early 1990s I remembered breaking SunOS5.0 on Sparc with such dirty tricks).

And on Linux, x86-64, with a decent machine, you really don't care. The stack is not that big ...

I assume the mmap -ed stack segment is with MAP_NORESERVE MAP_STACK MAP_GROWSDOWN , but I could be wrong.

+3
source

Source: https://habr.com/ru/post/1382159/


All Articles