First, a small clarification. Stacks are not necessarily in DRAM. they are just a structure that can be formed in any memory: DRAM, caches, disk.
To understand a stack, you should first understand what is a stack. It is like a stack of trays, the properties that make it a stack are:
- You can only access the top element of the stack
- It is Last In First Out, i.e., when you go to get a data from a stack you get the data that was stored last on the stack.
The act of storing something in a stack is called PUSH and removing it is called a POP. Say I do the following to an empty stack:
PUSH A
PUSH B
PUSH C
Then the stack will contain
C - Top
B
A
Now if I execute a POP (notice there is no operand here), it will return C and the stack will contain
B -- top of stack
A
So stack in processors is just a hardware implementation of the above algorithm.
A register contains the address of the top of stack called stack point
The ISA (Instruction Set Architecture) provides PUSH and POP instructions to access the stack variables as I showed above.
This is a very useful construct. A stack is used to store local variables, basically temporary data that you want to remove at the end of a function call. It specifically helps with function calls. When a function is called, the variables of the newly called function's local variables are pushed on the stack.
foo(){
int a;
int b; // both registers containing a and b are PUSHed here on the stack
c = bar(); // pop the stack to get value of c
print c
}
bar(){
int z; // local variables pushed on top of the stack
z = ...
return z; // pop all local variables of bar(), then push z on the stack
}
I hope the above helps.