Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursion Causing Stack Overflow???? 1

Status
Not open for further replies.

Spannerman

Programmer
Dec 31, 2000
26
GB
I am still pondering my problem with Stack Overflow understanding recursion.
I have a Database which I call Rstock with a menu with 16 options. I run the program
rstock.exe and the very first thing it does is run a function rmenu(). This puts up the menu of 16 different options. At the end of each option I return to the menu with
the command rmenu(). IS THIS RECURSION????

If this is indeed the root of my problem how do I overcome it??

I must add that I have had other menu driven databases before and not had this problem hence my thinking it was the large sort routine.
 
Yes, that is recursion, any time a function calls itself, it's recursion. Here's what happens, and you can see why you have your problem.

When a function calls itself, all of the variables used in that function are pushed onto the system stack, and if you keep calling yourself, the stack will overflow.

Look at the examples again, and notice that one of the points that I made is you must have a termination case if not, you just keep pushing stuff onto the stack until it bursts. If every time you run rmenu() you return rmenu(), think about what happens. Every time you call it you're dumping on the stack, but you never return 0 to allow the stack to be pushed back off.

What you need to do is use some sort of a while loop, and have a flag to exit. so do something like:
flag = true;
while(flag){

run code

if (user enters quit)
flag = false
}//end while.

That should only run one instance of the subroutine, not one for each choice... As always, I hope that helped!

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
You do have a recursion happening, with the process being so close to the main level, it's possible that you have a large stack to propogate.

As mbranski states, your rmenu function should be a loop with some termination flag, perhaps the subfunction returning a special value or maybe there's a quit on the menu. rmenu's job is not simply to select the menu item to run, but to do so until it's time to quit.

Since rmenu has now accepted the responsibility of looping, the subfunctions can forget about it.




Wil Mead
wmead@optonline.net

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top