rand_program
rand_program

Reputation: 1180

Stack Memory Adress Differences

i am new in c++.

I do have 2 code snippets.

FIRST

#include <iostream>

int main()
{
    int firstInteger = 1;
    std::cout << "First memory adress: " << &firstInteger << std::endl;
    int secondInteger = 2;
    std::cout << "Second memory adress: " << &secondInteger << std::endl;

    return 0;
}

Result is

First memory adress: 00000039A2F7F934
Second memory adress: 00000039A2F7F954

Second integer has a bigger hex value.

SECOND

#include <iostream>

void someFunction() {
    int secondInteger = 2;
    std::cout << "Second memory adress: " << &secondInteger << std::endl;
}

int main()
{
    int firstInteger = 1;
    std::cout << "First memory adress: " << &firstInteger << std::endl;
    someFunction();
    
    return 0;
}

Result is

First memory adress: 00000093953EF744
Second memory adress: 00000093953EF624

First one is bigger this time.


Can somebody explain what is the difference between them.

Thank you.

Upvotes: 0

Views: 47

Answers (1)

user17732522
user17732522

Reputation: 76658

There is no guarantee of any ordering or distance between addresses of different variables (or complete objects in general), except that the storage of the objects will not overlap while they are in their lifetime. The compiler is allowed to layout the stack however it considers reasonable and efficient. It is wrong to assume any ordering must be present.

For example on GCC 12.2 x64 without optimization flags enabled I get a smaller address for the second variable in both cases here, but your behavior with -O2 optimizations enabled here.

Upvotes: 4

Related Questions