简体   繁体   中英

What does a C++ address hex represent?

The following main() is one of my attempts at decoding the significance of pointer values:

int main(){
    int a = 15, b = 27;
    int *p = &a, *q = &b;
    cout << p << ',' << q;
}

The two values printed are hexadecimals, namely p = 0x28fef4, q = 0x28fef0 . These look like hex values, representing 2686708 and 2686704 in decimal.

This raises some questions, of which you may answer as many as you like.

  1. Why is q smaller than p ? I would expect memory to be assigned in ascending order, but q < p .

  2. Why do addresses rarely change? I ran a similar program a few hours ago, and I remember the address being 0x28fef4 that time too.

  3. What does one unit in the hex value represent? A bit? A byte?

  4. I have around 8 GB of memory (RAM). Why are the values of p and q so small compared to my RAM capacity?

Feel free to answer any or all of these questions, or to provide any related information about pointers.

Thanks.

Why is q smaller than p? I would expect memory to be assigned in ascending order, but q < p.

I'm not sure why you'd expect that. What possible difference could it make?

Why do addresses rarely change? I ran a similar program a few hours ago, and I remember the address being 0x28fef4 that time too.

Apparently your platform doesn't randomize stack addresses. Same stack, same addresses.

What does one unit in the hex value represent? A bit? A byte?

A byte.

I have around 8 GB of memory (RAM). Why are the values of p and q so small compared to my RAM capacity?

Physical memory has nothing to do with this. These are virtual memory addresses, not physical memory addresses.

I would expect memory to be assigned in ascending order

This expectation is totally unfounded. Compilers don't order things according to their order of appearance in the source code or other insignificant details.

Why do addresses rarely change?

Similar pieces of source code are often translated to similar pieces of target code. What's so surprising here?

What does one unit in the hex value represent? A bit? A byte?

A byte (but please bear in mind that "hex value" is a misnomer, values are integers, the notation is hex).

Why are the values of p and q so small

Your variables are automatic, which is the C way of saying "they are on the stack". Your compiler allocates the stack near the beginning of virtual memory adddress space. Every program has its own virtual memory address space so it's OK when two programs that run at the same time occupy the same range of virtual addresses.

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