Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
like image 863
김도윤 Avatar asked Mar 04 '23 06:03

김도윤


2 Answers

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.

like image 108
Jonathon Reinhart Avatar answered Mar 28 '23 06:03

Jonathon Reinhart


It depends on the Operating systems. But mostly (On most OSes) they are logical addresses. There are OS mechanisms like Virtual memory, Paging etc for address translation. This is usually done to ensure that a program is not allowed to overwrite parts of memory. If you are running this on a bare-metal kernel with no OS to handle the virtual address. It will be the physical address. If it is run as an application on top of an OS you will get Virtual addresses.

like image 28
Bhargav Kinnal Avatar answered Mar 28 '23 07:03

Bhargav Kinnal