There are four ways to look at this:
1) As simply a meaningless metaphor. Calling the newest element the top, bottom, or front of the stack is simply an idiomatic choice. I know for a fact some people think of it that way. And there top is the popular answer. And because of them you can't rely on the next way to look at this unless you check it yourself.
2) As an implementation detail. Stacks must change their address as they grow. A stack that grows must change its address in a particular way. A stack that grows up or down tells you if the address gets bigger or smaller as they grow.
3) As an implementation detail clouded by an idiomatic choice. Who the hell decides that the zeroth address is at the top or bottom of memory? Your computer certainly doesn't care. Go ahead, turn it upside down. Your memory bits don't fall out. Motherboards can be installed with any orientation so up really has no objective meaning here. I've seen instructors write it on the board either way. I seen books lay it out either way. I've seen specs lay it out either way. After over 20 years the only thing I know for sure is that I don't trust it.
4) Bigger numbers always go up. What are you stupid? Just like in graphics where they grow left to right, top to bottom... hey wait a second...
This interview question is a good example of how this can seem objective yet be arbirary. With local1
allocated in the first frame and local2
allocated in the second it's output code is:
if(local1 < &local2)
{
printf("\nStack is growing downwards.\n");
}
else
{
printf("\nStack is growing upwards.\n");
}
Yet in the first comment insists the inequality is pointing the wrong way. The second insists on dropping up/down and referring to higher/lower addresses.
My advice, if you're writing something that cares about this and you can't avoid it, carefully determine the popular assumptions and use those consistently. Try to make your assumptions clear.
If you're reading something that cares about this, regardless of context, don't trust assumptions until they are clear.
Stack depicted with 0th memory address at the top:
https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html
Stack depicted with 0th memory address at the bottom:
https://stackoverflow.com/questions/4560720/why-does-the-stack-address-grow-towards-decreasing-memory-addresses
Note how they give you the ability to check what their assumptions are.
It sucks but this ambiguity is what we've been left with. Anyone who says different is simply stuck in a small context.
If you want to sidestep all this confusion you can say exceptions unwind the stack.