Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does stack size in a thread define in C++?

I'm using C++ and Windows.h in my source code. I read the CreateThread API in MSDN, but I still don't understand the essence of specifying stack size. By default it is 1 MB. But what will happen if I specify 32 bytes?

What does stack size in a thread define?

Please provide a thorough explanation and I'll appreciate it. Thanks.

like image 458
user3009097 Avatar asked Nov 14 '15 10:11

user3009097


1 Answers

The stack is used to store local variables, pass parameters in function calls, store return addresses. A thread's stack has a fixed size which is determined when the thread is created. That is the value that you are referring too.

The stack size is determined when the thread is created since it needs to occupy contiguous address space. That means that the entire address space for the thread's stack has to be reserved at the point of creating the thread.

If the stack is too small then it can overflow. That's an error condition known as stack overflow, from which this website took its name. When you call a function some or all of the following happens:

  • Parameters are pushed onto the stack.
  • The return address is pushed onto the stack.
  • A stack frame containing space for the function's local variables is created.

All of this consumes space from the stack. When the function in turn calls another function, more stack space is consumed. As the call stack goes deeper, more stack space is required.

The consequence therefore of setting the stack size too low is that you can exhaust the stack and overflow it. That is a terminal condition from which you cannot recover. Certainly 32 bytes (rounded up to one page which is 4096 bytes) is too small for almost all threads.

If you have a program with a lot of threads, and you know that the thread's don't need to reserve 1MB of stack size then there can be benefits to using a smaller stack size. Doing so can avoid exhausting the available process address space.

On the other hand you might have a program with a single thread that has deep call stacks that consume large amounts of stack space. In this scenario you might reserve more than the default 1MB.

However, unless you have strong reason to do otherwise, it is likely best to stick to the default stack size.

like image 65
David Heffernan Avatar answered Sep 20 '22 06:09

David Heffernan