Note that there are some explanatory texts on larger screens.

plurals
  1. POProgram memory layout in linux
    primarykey
    data
    text
    <p>I am a bit confused on how a program looks like in memory , my professors told me that the stack and heap grow towards each other with the stack being at a lower memory address. </p> <p>First thing that bothered me with that image is that if the heap grew from high to low then if I allocated an array on the heap shouldn't a pointer to the second element be smaller in int value than a pointer to the first element ? which would be confusing</p> <p>I did a little research and I came upon this figure (note my question is focused on linux)</p> <p><a href="http://www.cyberplusindia.com/blog/wp-content/uploads/2008/10/memorysegment.gif" rel="nofollow noreferrer">layout http://www.cyberplusindia.com/blog/wp-content/uploads/2008/10/memorysegment.gif</a></p> <p>Ok, so Data and un-initialized data comes after the Text segment and are in the beginning of the program's memory then the heap followed by the stack and finally the command line arguments and environment.</p> <p>But if the stack grows from high addresses to low then how come if I have an array allocated on the stack a pointer to the first element will also be lower in value than a pointer to the second element ? doesn't that mean the stack would grow from low to high also ?</p> <p>So my question is what is the correct memory layout for a process in Linux? And also where does the memory for a shared library come from (in the process' address space)</p> <p>Simple code with pointer examples :</p> <pre><code>#include &lt;iostream&gt; int data[5]; int main() { using std::cout; using std::endl; int stack = 0; short *sptr = reinterpret_cast&lt;short *&gt; ( &amp;stack ); int *iptr = new int[5]; cout &lt;&lt; "Starting static tests" &lt;&lt; "\nPointer to first element " &lt;&lt; data &lt;&lt; "\nPointer to second element " &lt;&lt; &amp;data[1] &lt;&lt; "\nstarting stack test " &lt;&lt; sptr &lt;&lt; "\nsecond short " &lt;&lt; &amp;sptr[1] &lt;&lt; "\nStarting heap test " &lt;&lt; iptr &lt;&lt; "\nsecond int " &lt;&lt; &amp;iptr[1]; delete[] iptr; return 0; } </code></pre> <p>Output: </p> <pre><code>Starting static tests Pointer to first element 0x6013e0 Pointer to second element 0x6013e4 starting stack test 0x7fffdf864dbc second short 0x7fffdf864dbe Starting heap test 0x1829010 second int 0x1829014 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload