How do computers remember where they store things?

Question Detail: 

When a computer stores a variable, when a program needs to get the variable's value, how does the computer know where to look in memory for that variable's value?

Asked By : MCMastery
Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/64578

Answered By : jmite

I'd suggest you look into the wonderful world of Compiler Construction! The answer is that it's a bit of a complicated process.

To try to give you an intuition, remember that variable names are purely there for the programmer's sake. The computer will ultimately turn everything into addresses at the end.

Local variables are (generally) stored on the stack: that is, they're part of the data structure that represents a function call. We can determine the complete list of variables that a function will (maybe) use by looking at that function, so the compiler can see how many variables it needs for this function and how much space each variable takes.

There's a little bit of magic called the stack pointer, which is a register which always stores the address of where the current stack starts.

Each variable is given a "stack offset", which is where in the stack it's stored. Then, when the program needs to access a variable x, the compiler replaces x with STACK_POINTER + x_offset, to get the actual physical place it's stored in memory.

Note that, this is why you get a pointer back when you use malloc or new in C or C++. You can't determine where exactly in memory a heap-allocated value is, so you have to keep a pointer to it. That pointer will be on the stack, but it will point to the heap.

The details of updating stacks for function calls and returns are complicated, so I'd reccomend The Dragon Book or The Tiger Book if you're interested.

No comments

Powered by Blogger.