LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   When is the user stack allocated? (https://www.linuxquestions.org/questions/programming-9/when-is-the-user-stack-allocated-312229/)

moadon 04-11-2005 10:10 PM

When is the user stack allocated?
 
Hi,

Can anyone tell me during which part of compiling, linking and executing a "C" program is the stack allocated? I am thinking that it is allocated when linux loads the executable image into memory but I am unsure. Also, where does the stack get allocated to? Is there one stack at the end of user memory that every process shares or does each process get its own stack allocated in its own address space -- say at the end of the data segment?

Any help would be greatly appreciated!!

aluser 04-11-2005 11:28 PM

All of each processes memory is private to that process (baring use of mmap() or sys V shared memory, and excepting read-only and COWd pages which will appear to be private anyway...)

The rest of this is IIRC. The data segment is toward the bottom (low addresses) of your memory and the heap is above that, growing upwards. The stack is towards the top and grows downwards. It grows implicitly; that is, the process attempts to write to the page just below the limit of the current stack, causing a page fault, and the kernel allocates a page into that place before returning control to the process, just before the store which caused the fault. (This means the store sort of happens twice.)

You can get some more empirical information by printing addresses of variables you've put on the stack. e.g.

Code:

int foo;
int bar;
printf("address of foo is %p, address of bar is %p\n", &foo, &bar);

If the function is called recursively or you have several functions like this which call eachother, you should see the addresses grow downward.


All times are GMT -5. The time now is 03:01 AM.