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.
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
I did a little research and I came upon this figure (note my question is focused on linux)
(source: cyberplusindia.com)
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.
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 ?
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)
Simple code with pointer examples :
#include <iostream>
int data[5];
int main()
{
using std::cout;
using std::endl;
int stack = 0;
short *sptr = reinterpret_cast<short *> ( &stack );
int *iptr = new int[5];
cout << "Starting static tests"
<< "\nPointer to first element " << data
<< "\nPointer to second element " << &data[1]
<< "\nstarting stack test " << sptr
<< "\nsecond short " << &sptr[1]
<< "\nStarting heap test " << iptr
<< "\nsecond int " << &iptr[1];
delete[] iptr;
return 0;
}
Output:
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