Geckoo wrote: |
---|
The name seems to explain that the memory sections are available randomly - and it's not true. |
Do you realize that RAM is a piece of hardware?
Your whole program (the machine instructions, the stack, the heap, etc.) are normally stored in RAM while it is running, but modern computers use
virtual memory so there is nothing preventing the OS from swapping out some of it to disk for a while (usually only happens when you run out of free RAM). This does not affect the addresses you see in your program because those are
virtual addresses, not real physical addresses. It's even possible that two programs use the same
virtual addresses but they are being mapped to different physical memory locations.
That being said, the mapping of virtual memory is done in big chunks so it's likely that two virtual addresses that are close to each other are also close in physical memory.
So what decides what virtual memory addresses the objects get stored at?
Well, you probably already know that local variables are being stored on "the stack" and if you know how a stack works (that you can only "push" and "pop" at the top) then you should know why the addresses of local variables are not very random. For example, local variables declared in the same function normally ends up right next to each other, and a local variable declared in a loop will normally have the same address on each iteration.
As for objects created with new it's not so obvious. It's
not like "
hey, RAM give me a piece of memory to store my int!". Instead it's more like a function call, to a function written by your compiler/standard library implementers, to handle all this complicated stuff of keeping track of allocated memory, which is in use and which is free, and to find an appropriate piece of memory to let you use. I don't know exactly how it works, it depends on how it's implemented, but as far as I know there is no attempt at making the addresses appear "random". If the program doesn't have enough memory it can request more from the operating system (which is what handles the interaction between the hardware and the software) but this is done in large chunks so the addresses you get will mostly be down to how the new and delete "functions" happen to be implemented.