4

When a binary (C/C++) is executed under Linux,

  1. How is the stack initialized for the process?
  2. How does the stack grow and up to what limit?
  3. Using ulimit, I can have a limit number and by using setrlimit, I can modify it, but up to what limit, how can I determine it?
  4. Is the same stack size allocated for all executing processes?

As you can see in the code below, I have recursively called func() for push operation only, and the stack grew up to around approximately 8 MB. And it crashed (stack overflow!).

void func()
{
    static int i=0;
    int arr[1024]={0};
    printf("%d KB pushed on stack!\n",++i*sizeof(int));
    func();
}

int main()
{
    func();
    return 0;
}

output snippet:

8108 KB pushed on stack!
8112 KB pushed on stack!
8116 KB pushed on stack!
8120 KB pushed on stack!
Segmentation fault (core dumped)
  1. Where did these approximately 8 MB come from?
Community
  • 1
  • 1
SD.
  • 1,432
  • 22
  • 38

2 Answers2

2
  1. Stack is one of the various memory region that is associated to a process at startup time and may vary during runtime. Others can be text/code, heap, static/bss, etc.
  2. Each time you call a function the stack grows. A stack frame is added on top of it. A stack frame is what is necessary to a given function to be executed (parameters, return value, local variables). Each time you return from a function, the stack shrinks by the same amount it grew.
  3. You can try to estimate how deep you function call tree will be (f calls g which in turn calls h, depth is 3 calls, so 3 stack frames).
  4. Yes there is a default value that was estimated by OS designers. That size is in general sufficient.
  5. This is a default constant associated to your OS.
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
2
  1. How stack is initialized for its process?

It depends on the architecture, but in general, the kernel allocates some virtual memory in your process's VM, and sets the stack pointer register to point to the top of it.

  1. How stack grows and up to what limit?

Every function call reserves more space on the stack using an architecturally defined procedures. This is typically referred to as a "function prologue".

  1. Using ulimit, I can have limit number and using setrlimit, I can modify it but up to what limit, how can I determine it?

ulimit -s will tell you the maximum stack size (in KB) for the current process (and all child processes which will inherit this value, unless overridden).

  1. Does same stack size is allocated for all executing process?

See previous answer.

Related:

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328