So, a computer has K bytes of physical memory. When a process starts, the OS loads the code into physical memory, at an address unknown to us. It then uses a function (usually implemented in hardware) to map the addresses that we (the process) see to physical ones and vice versa. This function is used for instructions, stack memory, heap memory, etc; every single address goes through this function.
This means that the reason we can't write at address 0 is not because some other crucial piece of data is stored at it, and the OS is preventing us from overwriting it; when we try to write at 0, that 0 goes through the mapping function, and we are actually trying to write to a perfectly regular address in physical memory.
Is this correct so far? If I take a look at this image:
I can see that the OS leaves a gap between address 0 and the lower limit of the stack; We can't ever write to this gap "because the OS said so", probabily for security reasons if I had to guess.
This also means that the reason that the same piece of data (instruction or variable) is stored at different locations on different runs of the same program is also a totally arbitrary OS decision. It is not, as I though for a long time, because the addresses used on the previous run are now being used by someone else. The OS chooses to make us start in a different place, again "because security".
But what, exactly, does this mean? Just that the gap at the start is bigger or smaller, and everything else shifts accordingly? It's not that the stack and the heap are swapped around or something, that can't happen, right?
The final question is about something Casey did on the earlier days of HH:
// Inside WinMain() ... void *DesiredAddress; #if HANDMADE_INTERNAL DesiredAddress = Terabytes(2); #else DesiredAddress = 0; #endif void *Memory = VirtualAlloc(DesiredAddress, ...);
Why 2 terabytes? If process layouts are randomized, how can you be sure that what you're asking for is heap memory? Maybe the randomization is limited, and that is an address that he just knew was going to be ok. But also, while watching the video (Day 14 if I'm not mistaken), I had the impression that he just chose it arbitrarily, and any other address would've worked just as well... which isn't really true, since you have to pick an address that's in the heap section, right?