Search code examples
cpointersmemoryvirtual

Do pointers refer to physical or to virtual memories?


I recently learned that computer programs do not actually make use of the physical memory's address. Rather, I understand that the physical memories are 'hidden' by the operating system to the application.

Here comes my question: Do pointers return the address of the physical memory or the virtual memory?

If I execute the code below, I get a hexadecimal form of an address. Is it just a number that was randomly assigned by the operating system? And also, I found out that the addresses of the elements in an array are assigned successively. Does this mean that an array is actually in a 'line' form in the RAM, or is it possible for them to be assigned in sparse regions and the OS merely fakes the programmer?

int num = 3;
int arr[3];

printf("address of num: 0x%0x \n", &num);
printf("&arr[0]: 0x%0x \n", &arr[0]);
printf("&arr[1]: 0x%0x \n", &arr[1]);
printf("&arr[2]: 0x%0x \n", &arr[2]);

Solution

  • In all modern OSes (Windows, Linux, BSD, etc), all addresses in a userspace application are virtual addresses. The exceptions to this are certain RTOSes or other custom bare-metal applications.

    Virtual addresses are not necessarily random, but from the perspective of the hardware they are arbitrary. The kernel will typically decide the virtual address space to allocate for a given mapping request, sometimes taking userspace requests into account. When things like ASLR are used (which is common nowdays), the addresses are intentionally randomized.

    Does this mean that an array is actually in a 'line' form in the RAM, or is it possible for them to be assigned in sparse regions and the OS merely fakes the programmer?

    Both. The OS creates physical-to-virtual mappings of pages of memory, not individual addresses. The page size varies by architecture but is commonly 4 KiB.

    So if you have a 1 KiB array (whose starting address is at least 1 KiB aligned), it will be physically contiguous. A 16 KiB array however could be scattered across 4 pages that are nowhere near each other.