Consider the really simple code below:
#include <stdio.h>
#include <stdlib.h>
int main() {
int* a = (int*) malloc(10 * sizeof(int));
printf("a = %p, a+1 = %p", a, a+1);
return 0;
}
The output is this:
a = 0x127f190, a+1 = 0x127f194
Since the size of an int is 4 bytes, I am assuming from the result above that a pointer value is then the index of a byte on my RAM memory. Hence a+1 increases in fact the value of a by sizeof(int) = 4 (bytes). Is that correct?
If yes, then why do I get 32 bit memory addresses from my program? This machine is 64bit running a 64bit version of Ubuntu. How do I get the program to print a full 64bit address? Do I have to compile it with special flags?
That’s close enough for most purposes, but not entirely accurate. It’s the index of a byte in your process’s address space. Virtual addresses do not relate directly to physical RAM, there’s a thing called a “virtual memory manager” that’s responsible for keeping track of what virtual addresses in each process refer to what physical RAM (and things other than RAM).
Normally you can forget about this, and just think of the virtual address space as RAM (or as “memory” to keep it abstract). But the same virtual address in different processes could refer to different physical memory, or the same memory could be referred to in different processes by different virtual addresses. Or the same virtual address in the same process could refer to different physical memory at different times, if the OS has noticed that the page hasn’t been used for a while, swapped it to disk and then back to memory when it’s used again. So it’s not really “the” address of the RAM itself, it’s just the address that your process has been given by the OS, to refer to some RAM.