Stack allocation limit for programs on a Linux 32 bit machine

后端 未结 3 1485
礼貌的吻别
礼貌的吻别 2021-01-16 11:45

In C++ how much can the stack segment grow before the compiler gives up and says that it cannot allocate more memory for stack.

Using gcc on a linux (fedora) 32 bit

3条回答
  •  感情败类
    2021-01-16 12:03

    Windows (and I think Linux) both operate on the big stack model assumption, that is, there is one stack (per thread) whose space is preallocated before the thread starts. I suspect the OS simply assigns virtual memory space of the preallocated size to that stack area, and adds real memory pages underneath as the end of the stack is advanced beyond a page boundary until the upper limit ("ulimit") is reached.ck

    Since OSes often place stacks well away from other structure, when ulimit is reached, it is just possible that the OS might be able to expand the stack, if when the overflow occurs nothing else has shown up next to the stack. In general, if you are building a program complex enough enough to overflow the stack, you are likely allocating memory dynamically and there is no gaurantee that the area next to the stack didn't get allocated. If such memory is allocated, of course the OS can't expand the stack where it is.

    This means the application cannot count on the stack being expanded automatically by the OS. In effect, the stack can't grow.

    In theory, an application exhausting its stack might be able to start a new thread with a larger stack, copy the existing stack and continue, but as practical matter I doubt this can be done, if for no other reason than pointers to local variables stack will need adjusting and C/C++ compilers don't make it possible to find such pointers and adjust them. Consequence: ulimit has to be declared before the program starts, and once exceeded, the program dies.

    If one wants a stack that can expand arbitrarily, it is better to switch to a language that uses heap-allocated activation records. Then you simply don't run out until your address space is used up. 32 or 64 bit VM spaces ensure you can do a lot of recursion with this techniquie.

    We have a parallel programming language called PARLANSE, that does heap allocation to enable thousands of parallel computational grains (in practice) to recurse arbitrarily this way.

提交回复
热议问题