简体   繁体   中英

How is thread stack created in C?

Let's say we have the following program:

int main() {
   pthread_t tid;
   Pthread_create(&tid, NULL, thread, NULL);
   Pthread_join(tid, NULL);
   ... //do some other work                    
   exit(0);
}

void *thread(void *vargp) {
   ...//do sth
   return NULL;
}

Below is a picture that shows the main thread stack: 在此处输入图像描述

My question is, after a new thread is created, how does the new thread's own stack look like? does the beginning of the new stack start right after the main thread as: 在此处输入图像描述

or the new thread's stack's beginning address can be any random address, therefore leaving "splinters" as:

在此处输入图像描述

I know due to virtual address, the virual pages can be anywhere in the physical disk, but I just want to know if the virtual address itself is continuous or not.

This depends on the operating system.

For security reasons, the layout of the virtual address space is randomized in most modern operating systems. This is called Address Space Layout Randomization (ASLR) .

Therefore, it is unlikely that the virtual memory reserved for the thread's main stack will be directly adjacent to that of another thread. Even without ASLR, there will probably be at least one guard page (probably more) between the two stacks to detect and protect against a stack overflow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM