简体   繁体   中英

Can a pointer point to an address after 4GB?

If we compile and execute the code below:

int *p;
printf("%d\n", (int)sizeof(p));

it seems that the size of a pointer to whatever the type is 4 bytes, which means 32 bit, so 2 32 adresses are possible to store in a pointer. Since every address is associated to 1 byte, 2 32 bytes give 4 GB.

So, how can a pointer point to the address after 4 GB of memory? And how can a program use more than 4 GB of memory?

By principle, if you can't represent an address which goes over 2^X-1 then you can't address more than 2^X bytes of memory.

This is true for x86 even if some workarounds have been implemented and used (like PAE ) that allows to have more physical memory even if with limits imposed by the fact that these are more hacks than real solutions to the problem.

With a 64 bit architecture the standard size of a pointer is doubled, so you don't have to worry anymore.

Mind that, in any case, virtual memory translates addresses from the process space to the physical space so it's easy to see that a hardware could support more memory even if the maximum addressable memory from the process point of view is still limited by the size of a pointer.

To access >4GB of address space you can do one of the following:

  • Compile in x86_64 (64 bit) on a 64 bit OS. This is the easiest.
  • Use AWE memory . AWE allows mapping a window of memory which (usually) resides above 4GB. The window address can be mapped and remapped again and again. Was used in large database applications and RAM drives in the 32 bit era.

Note that a memory address where the MSB is 1 is reserved for the kernel. Windows allows under several conditions to use up to 3GB (per process), the top 1GB is always for the kernel.

By default a 32 bit process has 2GB of user mode address space. It's possible to get 3GB via a special linker flag (in VS: /LARGEADDRESSAWARE).

"How can a pointer point to the address after 4GB of memory?"

There is a difference between the physical memory available to the processor and the "virtual memory" seen by the process. A 32 bit process (which has a pointer of size 4 bytes) is limited to 4GB however the processor maintains a mapping (controlled by the OS) that lets each process have its own memory space, up to 4GB each.

That way 8GB of memory could be used on a 32 bit system, if there were two processes each using 4GB.

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