Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

multithreading - 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: enter image description here

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: enter image description here

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

enter image description here

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.

question from:https://stackoverflow.com/questions/65881180/how-is-thread-stack-created-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...