3.16 The layout of the Stack Area

Before we tell you how to obtain information on the Stack Area, we first have to explain you how it is layed out. We've already seen that there are two stacks: the Data Stack and the Return Stack. We also know what they are used for.

The next question is what part of the Stack Area is used by the Data Stack and what part is used by the Return Stack. In fact, both stacks share the very same Stack Area.

The Data Stack grows upward from the bottom and the Return Stack grows downward from the top. When they meet, you're in trouble. If the Return Stack causes the overflow, 4tH will report that the Return Stack overflowed. If it was the Data Stack, it will report that the Data Stack overflowed.

If an overflow happens, you can't say which stack actually overflowed. If the Data Stack filled up the Stack Area and a colon-definition tries to put a return address on the Return Stack, the Return Stack will get the blame.

Now for the good news. Because of this shared stack space, programs with different requirements can run without having to modify stack sizes (you can't do that; only the programmer of your application can). It can be a program that heavily uses the Return Stack (recursive colon-definitions) or a program that needs lots of data on the Data Stack.

What you can check is how big the Stack Area actually is. It is a constant named 'STACK'. It will report the size in cells. Every value on any stack (address or value) takes up a single cell.

You can also ask 4tH how many values are on the Data Stack using 'DEPTH'. It will report the number of values, before you executed 'DEPTH'. Let's elaborate on that a little more:

     ." Begin" cr    ( no values on the stack)
     10              ( 1 value on the stack)
     5               ( 2 values on the stack)
     9               ( 3 values on the stack)
     depth           ( 4 values on the stack)
     . cr            ( 4tH reports "3")

If you want to know what values the actual stack pointers have, you have to use 'SP@' and 'RP@'. By subtracting 'SP@' from 'RP@' you can see how much space is left in the Stack Area:

     rp@ sp@ -
     ." Space left: " . ." cells" cr