Return stack operations generate “invalid memory address” in Gforth 0.7

StackOverflow https://stackoverflow.com/questions/7940501

  •  16-02-2021
  •  | 
  •  

Question

I'm learning Forth here, and I've got onto return stack operations.

So using the console on Ubuntu 11.04 x64 I am trying to get the TOS onto the return stack but this happens:

1 2 3 4 5 ok
>r 
:36: Invalid memory address
>R>>><<<
Backtrace:

What am I doing wrong here?

Was it helpful?

Solution

>r is itself a word and needs to return to the interpreter. When >r is executed as in the question it adds a new return address, an invalid one.

Instead use >r inside a (new) word. Note that the items added to the return stack must be removed before that word ends - the return stack must be in the same state as when the word started executing.

Loops are actually an example of an application of the return stack inside words (and thus your own use of the return stack must also be balanced within loops just as it must be balanced within a word).

OTHER TIPS

What you are trying to to do doesn't really make much sense. A forth machine executes a series of words, the address of the next word in line to be executed is stored in a special register called NEXT (think of it like the instruction pointer of a CPU).

A return stack is needed because, if a call is made to a word that is itself a threaded list of words, then you would end up scrubbing the original address in NEXT register - to stop this from happening, the current contents of the NEXT register are pushed into the return stack.

If I understand correctly >r pushes the top element of the data stuck onto the return stack; in this case, '5' is not valid, because, there are no instructions at the address '5'.

As someone else has pointed out you don't need to be concerned about the return stack, unless you are implementing new control constructs.

You can use the return stack in Gforth in the command line (that's a non-standard feature), with one limitation: It has to be balanced within one line. At the end of the line, the line interpreter is going to return, and therefore, the return stack must contain the expected return address.

So try something like

1 2 3 4 5 >r + r> .s

which should give you

1 2 7 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top