0

In the following code, I am wondering why the order of allocation is "c, b, a" and not "a, b, c", as I can see from the variables' adresses

#include <iostream>

using namespace std;

int main()
{
    int a, b, c;
    cout << "address a: " << &a << '\n';
    cout << "address b: " << &b << '\n';
    cout << "address c: " << &c << '\n';
    return 0;
}

The output is the following:

address a: 0x28fefc
address b: 0x28fef8
address c: 0x28fef4

Process returned 0 (0x0)   execution time : 0.056 s
Press any key to continue.
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
razvanw0w
  • 11
  • 2
  • 2
    So the memory addresses decreases... It is still consistent with "a, b, c" if the stack is ordered from an end address and going "up" by decreasing the top of the stack. But, are you sure you have the right to infer the order of allocation from the values of memory addresses? – coredump Nov 27 '16 at 17:49
  • 6
    In general, the stack always grows down, so a "left-to-right" allocation would actually produce an in-memory ordering of c, b, a—just like you're seeing. But as far as I'm aware, neither the C nor C++ language standards makes any guarantees about this, so your investigation does not really show anything useful. – Cody Gray - on strike Nov 27 '16 at 17:51
  • @coredump I thought they will be allocated in a contiguous segment of memory. Besides, the idea of allocation from the top of the formed stack sounds legit.. – razvanw0w Nov 27 '16 at 17:53
  • @CodyGray so are you telling me that the decreasing order of memory addresses might not be related to the order of allocation? – razvanw0w Nov 27 '16 at 17:56
  • 5
    I don't know how to say it any more clearly. Automatic/local variables are allocated on the stack, and the stack almost always grows *downwards* in memory, from high addresses to low addresses. Therefore, if you allocate space for `a` first, it will have a higher address in memory than space for subsequently allocated objects, like `b` or `c`. But I also was trying to emphasize that this is not something you should concern yourself with, because the language standard doesn't make any guarantees here. The guarantee is that the requested space will be allocated, and it is. You don't care where. – Cody Gray - on strike Nov 27 '16 at 18:00
  • It's also worth mentioning that they _are_, in point of fact, allocated continuously. In hex, `4 + 4 = 8`, `8 + 4 = c`. So they are being allocated in contiguous blocks of size 4. – Harper Nov 27 '16 at 19:03

0 Answers0