简体   繁体   中英

Why not memory address of an array always increase?

Tried following code on 32 bit ubuntu virtual machine:

static int a[0x1f0fff];
cout << &a[0x600000] << endl;
cout << &a[0x800000] << endl;
cout << &a[0x8fff00000] << endl;

0x984a140
0xa04a140
0x7c4a140

Really confused that the address do not keep increasing.

The array located in heap, and what printed is virtual memory address. Is it because that it exceeds virtual memory space?

Besides, according to another answer , the last two line codes are indexing into a part of memory that is not allocated . Why is there no segfault reported?

Your hexadecimal notation, whilst flashy, is no more than an obfuscation (although the type inference rules for hexadecimal literals differ from denary literals).

The behaviour of your code is undefined but perhaps not for the reason that you might think.

Note that &a[0x600000] doesn't actually attempt to dereference the non-existent (0x600000)th element of a before taking the address of it. The compiler is required to evaluate the expression as a + 0x600000 . But:

Setting a pointer to an address that is not an element within your array a , or one past the end of that array is undefined behaviour. As such the compiler is allowed to output anything.

Undefined behaviour is not segfault. You hope for segfault. Sometimes you get nasal demons.

Why this particular behaviour? 32 bit unsigned math mod 2^32. Not guaranteed to happen, but I am pretty certain that is what the compiled result is doing here.

Besides, according to another answer, the last two line codes are indexing into a part of memory that is not allocated. Why is there no segfault reported?

Accessing array out-of-bound is undefined behaviour, that means anything can happen, and that also means there is NO guarantee of a segfault - it may happen one time, it may not happen the next time (that's why it's called undefined).

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