Search code examples
cmultithreadingmemorystack-memory

Thread stack allocation


We know that each thread has its own stack. Where are these stacks allocated? I read some documents, it seems the stacks are allocated from heap when a thread is created. Does this make sense? Thanks in advance!


Solution

  • C doesn't specify where the memory comes from. It's dependent on the OS and the C runtime library. Either thread stack memory is allocated by the operating system as part of the system call that creates a thread, or the process creating the thread has to provide memory from the application heap to be used as thread stack.

    Looking at the documentation for the Linux clone syscall, it appears that Linux does the latter; thread stack memory comes from the application heap.

    Why do you ask?