简体   繁体   中英

Why aren't consecutively-defined variables in increasing memory locations?

If we take the following code:

int height = 10;
int width = 5;
printf(
    "The memory address of height is: %p\n"
    "The memory address of width is:  %p\n",
    &height, &width
);

I get the following prints:

The memory address of height is: 0x7ffeed809a78
The memory address of width is:  0x7ffeed809a74

I was expecting the width to be at location 0x7ffee8843a7c . In other words it's doing &height - 1 instead of &height + 1 . Why is that so?

There's no reason for them to be, so the compiler does what's best for itself.

Complex compiler optimizations and efficient and linear memory layout don't all go together, so linear memory layout was sacrificed.

When you get to hashtables, you will learn how the most efficient algorithms lead to repeatable pseudo-random output order. The symbol names are loaded into a hashtable when compiling; and the function memory space could laid out by iterating over the global symbol table, which is therefore in some arbitrary order.

In general you will find this is true. Whenever the order isn't specified it will be let to fall however, and when algorithms are non-trivial, however isn't simple anymore.

Don't ever depend on order of symbols in memory layout. It's not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM