I want to know the way variables are allocated on stack, so i make a small test program
#include <iostream>
#include <stdlib.h>
using namespace std;
class test
{
public:
test()
{
}
test(const test &obj)
{
cout << "a clone of test has been created" << endl;
}
};
void foo(test variable_01, test variable_02)
{
cout << "v3 and v4 have not been created" << endl;
char variable_03;
char variable_04;
cout << "v3 and v4 have been created" << endl;
cout << "Adrress of variable 01: " << static_cast<void*>(&variable_01) << endl;
cout << "Adrress of variable 02: " << static_cast<void*>(&variable_02) << endl;
cout << "Adrress of variable 03: " << static_cast<void*>(&variable_03) << endl;
cout << "Adrress of variable 04: " << static_cast<void*>(&variable_04) << endl;
}
int main()
{
test temp;
foo(temp,temp);
return 0;
}
And here is the result
a clone of test has been created
a clone of test has been created
v3 and v4 have not been created
v3 and v4 have been created
Adrress of variable 01: 0xbf9dd3ae
Adrress of variable 02: 0xbf9dd3af
Adrress of variable 03: 0xbf9dd37e
Adrress of variable 04: 0xbf9dd37f
We have two groups of variable here
- Copies of pass by value variables : v_01 & v_02 (G1)
- Local variables : v_03 & v_04 (G2)
Base on the result, we know G1 have been allocated before G2 (maybe v_01 -> v_02 -> v_03 -> v_04). However there are a some strange things :
- Every variable in each groups are allocated continuously, but G1 and G2 are seem to be a bit far from each other , I think they should all be 0xbf9dd3a_ or 0xbf9dd37_ or { 0xbf9dd3ae -> 0xbf9dd3b1} or { 0xbf9dd37e -> 0xbf9dd381}
- Address of G1 is always greater address of G2. I can explain this base on the way stack work and data segment of a program when loaded. Here is a shortcut of data segment of a loaded program (source : http://www.inf.udec.cl/~leo/teoX.pdf ) .
- However if my explanation above is right, I can't explain why in each groups, address of variables are base on the time they have been created. (ex : v_03 before v_04, so v_04's address is greater than v_03's one)
Why address of G1 is greater G2, despite being created before G2?
Why variables in each groups are allocated continuously, but these groups are a bit far from each other?
Why address of variables in groups have different order compare to address order between these groups?