Recursive method cause stackoverflow - c#

I have a simple methode like this:
public int method(int a)
{
if(// something)
{
methode(a);
}
else return 0;
}
When the depth of calling increases, Visual Studio throws a stackoverflow exeption.
How can i solve this problem?
Is there any way to save return address and local data manually and implement a customized stack??
I should note that I don't want to change my method to non recursive type.

Yes, in C# (and probably in Java etc) there is a Stack<​T> class. For your method you can simply create a Stack and store the argument there. Iterate over the Stack until it's empty.
While this introduces an iterative loop, your algorithm is still recursive. (That is, depth first instead of breadth first)
Of course you need to make sure that your algorithm terminates eventually. This is just a way to increase stack space above what the operating system gives you. Windows allocates a certain amount of stack space for each process that suffices for most applications. If you need more, you can implement your own stack-like data structure on the heap. The heap is generally limited by the available RAM and the "bitness" of your application.

How can i solve this problem? Is there any way to save return address
and local data manually and implement a customized stack??
Recursive method should have a termination point, where from result is returned.

You need to decrease the depth of recursion.

public int method(int a ){
//do stuff
var something = ... //you have to make sure something turns false at some point
if(something){
method(a);
}
}

Like Dunken says - "you have to make sure something turns false at some point".
#define MAX 1000
#include <iostream>
using namespace std;
int methode(int a ){
if(a>0 && a<MAX) return methode(a);
return 0 ;
}// end
int main(void){
methode(1);
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}

Related

Replacing while-loop with recursion

Quick and simple question:
Is this:
private static void SetupConnection()
{
try
{
TcpClient client = new TcpClient(myServer, myPort);
//Do whatever...
}
catch (SocketException)
{
//Server is closed. Retry in 10 minutes.
Thread.Sleep(600000);
SetupConnection();
}
a viable alternative to this:
private static void SetupConnection()
{
while (true)
{
try
{
TcpClient client = new TcpClient(myServer, myPort);
//Do whatever...
break;
}
catch (SocketException)
{
//Server is closed. Retry in 10 minutes.
Thread.Sleep(600000);
}
}
}
While the second one looks "cleaner" I am still rather curious if the first one is also acceptable – and if it isn't, then why not?
Recursion is bad in this case, because if your program runs for too long and connection is retried, you will eventually hit a StackOverflowException.
Why Recursion is Bad ?
You will need to understand what is call stack.
This is a stack which is maitained in the memory. Every time a new method is called, that method's reference and parmaeters are added in this stack. This stack will be maintained in memory (RAM).
With recursion, if you keep on calling method without any boundary condition, the stack will keep on growing.
After some time, it would be in a state where it cannot accept any further entries because there is not enough memory to hold it.
That's when you will get "Stack Overflow Exception".
Can we rewrite every recursive algorithm without using recursion ?
Yes you can. The aproach is generally called as "Iterative approach".
In every case, you can use an auxillary stack / list / group of variables - to hold the parameters you were using in recursion.
Then you can iterate over these variables, until you reach the boundary condition.
That way, you can achieve the same result without calling your method again and again.
It is always better to use this approach.
Then why people write recursive algorithms ?
Sometimes, recursive algorithm is very easy to read. Iterative approach code may not be easy to read and that's why people try to write recursive code many times.
You can decide whether to use iterative approach or recursive approach based on two things:
Input samples
Code maintainability
If you still want to write recursive method, DO NOT forget to add the boundary condition after which recursion will stop.
For ex. Tree travesal code (pre order, in order , post order) is easier to understand if you write recursive algorithm.
This will work fine as long as you have some limit on number of nodes / levels in the tree. If you already know that your tree is very huge, probably you would go for iterative aproach.
Hope this helps you to understand these approaches better.

Compare parameters of multiple callbacks

I am programming a game using the Unity Engine and I am currently running into the following problem:
I have a method that asynchronously returns his result using the parameters of a callback function. Pretty straightforward, it looks like this:
public void CalculateSomething( - PARAMETERS - , Action<float> callback)
I have to call this method in a loop for different parameters.
foreach(float f in manyFloats){
CalculateSomething(f, myCallback);
}
void myCallback(float f){
...compare this result value to the other values?...
}
Now I would like to compare the resulting floats, that come with the different callbacks. Let's just say I want to find the highest value among those floats. How do I do that?
I had the idea to store the results in an array field and just compare after it is fully filled, but I don't know how to check if all callbacks are done already.
Ideally I'd like to avoid polluting my class with a field like this, but it would be alright if there is no other way.
The CalculateSomethingfunction is part of a library, so I can't change it. Everything else is variable.
Here is the deal.
You got it right about creating the array and storing the values and compare them when all callbacks are done. Hence the problem is that you don't know when all the callbacks are returned. But you know how many callbacks are there based on count of your origin manyFloats variable. All you need to do is keep a counter and add it up every time a callback is returned. And check if it equals the count of manyFloats then you can do the comparison:
int count = 0;
void myCallback(float f)
{
... usual stuff
... then
if(count == manyFloats.Count)
{
// do the comparison
}
else
{
count ++;
}
}
Rather than using a callback based model you should use a Task based model. Have CalculateSomething return a Task<float> instead of having a callback. This allows you to use the TPL to compose these Task objects by writing code like:
var highestResult = (await Task.WhenAll(manyFloats.Select(CalculateSomething))).Max();
If you can't edit the method itself, then create your own wrapper that transforms the method into a task based version.
So, if we have no control over CalculateSomething function, we still can store max value and make comparison in our callback. Something like this:
void callbackFunction( float numb){
if (numb > maxNumb) //maxNumb is global
maxNumb = numb;
}
then you can use your foreach loop to go through your array. Just keep in mind that you would need to declare your maxValue global variable and make it initially equal to minimum value.
Even if you are not doing Min/Max comparison, and it is something more complicated, you still can do it in callback function. No need for arrays, because even with arrays if you can do it with single pass through array - you can do it in a callback function.

Using ConcurrentBag correctly

Edit: Thank you, you made me realise that the code below is not working as I assumed, since somehow I thought that cbag works like a hashset. Sorry about it, you saved me some headache :)
the following function is the only function that can change _currentSetOfStepsProcessing. This function can be called from different threads. I am not sure if I understood correctly the use of a ConcurrentBag, so please let me know if in your opinion this can work. _stepsToDo datastructure is never modified once the process starts.
void OnStepDone(InitialiseNewUserBase obj)
{
var stepToDo = _stepsToDo[_currentSetOfStepsProcessing];
stepToDo.TryTake(out obj);
if (stepToDo.Count == 0) //can I assume it will enter here once per ConcurrentBag?
{
if (_currentSetOfStepsProcessing < _stepsToDo.Count - 1)
{
_currentSetOfStepsProcessing++;
}
}
}
List<ConcurrentBag<InitialiseNewUserBase>> _stepsToDo = new List<ConcurrentBag<InitialiseNewUserBase>>();
Action _onFinish;
int _currentSetOfStepsProcessing;
stepToDo.TryTake(out obj); might fail, you don't handle that.
Why are you out-referencing the method argument? This simply overwrites the argument. Why take an argument if you throw it away? More likely, this is a misunderstanding of some kind.
can I assume it will enter here once per ConcurrentBag since access to the bag is apparently concurrent multiple accessing threads might see 0. So yes, you need to handle that case better.
Probably, you should not make things so difficult and use lock in combination with non-concurrent data structures. This would only be a good idea if there was a high frequency of bag operations which seems unlikely.
What about this:
foreach (/*processing step*/) {
Parallel.ForEach(/*item in the step*/, x => { ... });
}
Much simpler.

Can't figure out how this method produces garbage and how to fix it

I've got a method that I'm calling ... well, very often. And now the GC is becoming a problem, because apparently this method is creating garbage, but I can't seem to figure out why.
Item item;
foreach (Point3D p in Point3D.AllDirections)
{
item = grid[gridPosition + p];
if (item != null && item.State != State.Initialized)
else
return;
}
OtherMethod(this);
This method is inside the Item class and figures out the state of neighbouring items. The gridPosition variable is obviously the position of this item inside the grid and the Point3D is a struct that just contains 3 ints, one for each axis. It also contains a few predefined static arrays such as AllDirections which itself only contains Point3Ds.
Now, the state of items can change at any time and once all neighbours have a specific state (or rather aren't in the Initialized state) I do some other stuff (OtherMethod), which also changes the state of the item so this method is no longer called. As such the produced garbage is only a problem when neighbours don't change their state (for example when there is no user input). I guess you could think of this as a substitution for an event driven system.
I admit that I have a rather limited understanding of memory management and I tend to only really understand things by doing them, so reading up on it didn't really help me much with this problem. However, after reading about it I got the impression that every value type, that is defined within a method and doesn't leave it, will be collected upon leaving the method. So I have a little trouble figureing out what's actually left after the return.
Any ideas on what's actually generating the garbage here ? Of course the best case would be to produce no garbage at all, if at all possible.
(Just in case this is relevant, I'm working in Unity and the method in question is the Monobehaviour Update)
Edit for all the comments:
Holy cow you guys are quick. So...
# Jeppe Stig Nielsen: There is nothing between if and else, there was once but I didn't need that anymore. It's just a quick way to leave if no neighbour was found. Also, Indexer ! Completely forgot about that, here it is:
public Item this[Point3D gridPosition]
{
get
{
Item item;
items.TryGetValue(gridPosition, out item);
return item;
}
}
Could the TryGetValue be the reason ?
# Luaan: I already tried a normal for loop, didn't change anything. That looked something like this:
for (int i = 0; i < 6; i++)
{
item = grid[gridPosition + Point3D.AllDirections[i]];
}
If it was the enumerator, that should've fixed it, no ?
# Rufus: Yes that's a better way to write the if, will fix that. The whole thing is a work in progress right now, so that's just a remnant of past experimentation. There is currently is nothing else in the if statement.
# Tom Jonckheere: Well there isn't really much else. It's just Unitys Update() followed by two if statements for the State. And that's really just because I currently only work with two states but have already setup more, so someday there will probably be a switch instead of ifs.
# Adam Houldsworth: Well yes, the problem is certainly that I call it so often. The odd thing is, the amount of garbage produced varies wildly. As far as I can tell it's in the range of 28 bytes to 1.8KB. As for the whole red herring thing, I don't think that's the case. The profiler points to the Update method, which only contains two ifs, one which is the code from above, the other one isn't being used when no state changes occur. And when testing, there are no state changes, except for intial setup.
Also, sorry for the wrong tag, first time I've visited this site. Looks like I'll have some reading to do :)
foreach calls GetEnumerator, which, in turn, creates a new instance of Enumerator every time it's called.
So after Jeppe Stig Nielsen and Luaan made me remember that I'm infact using an indexer I did some googleing and found out that this is not a new issue. Apparently Dictonary.TryGetValue works by calling Equals(object o) on the keys. Now these have to be unboxed which, as far as I understand it, creates the garbage. I now followed the advice I found on Google and implemented the IEquatable interface in my Point3D struct, which does not requiere any boxing. And as it turns out, a big chunk of the garbage is gone.
So the generated garbage per call went from ~28B-1.8KB down to ~28B-168B. Which is pretty good, no more GC spikes. Though I'm still curious where the rest of the garbage is coming from.
Anyway, this was already a big help, so thanks for your answers guys.
Edit: Figured out where the rest of the garbage was comeing from. I just called base.GetHashCode, because I didn't know any better. I did some research into pretty much everything related to hash codes and then implemented it correctly. And now I'm down to exactly 0 bytes of garbage. Pretty neat.

Stack<> implementation in C#

I've recently been implementing a recursive directory search implementation and I'm using a Stack to track the path elements. When I used string.Join() to join the path elements, I found that they were reversed. When I debugged the method, I looked into the stack and found that the elements themselves were reversed in the Stack's internal array, ie the most recently Push()ed element was at the beginning of the internal array, and the least recently Push()ed element was at the end of the internal array. This seems ass-backward and very counter-intuitive. Can somebody please tell me why Microsoft would implement a stack in such a manner ?
I think you're mistaken.
It isn't that Stack<T>.Push internally inserts an item at the start of its internal array (it doesn't). Rather, it enumerates from the top to the bottom, as this is the manner in which one would intuitively enumerate through a stack (think of a stack of pancakes: you start at the top and work your way down).
If you look at the contents of a collection from within Visual Studio's debugger, I think it will display them to you in the order they're enumerated -- not the order they're stored internally*.
Take a look at the Stack<T>.Push method in Reflector and you'll see that the code is basically exactly what you'd expect:
// (code to check array size)
this._array[this._size++] = item;
// (code to update internal version number)
So the stack internally adds new elements onto the end of its internal array. It's the Stack<T>.Enumerator class that's got you confused, not the Stack<T> class itself.
*I don't know whether this is true in general, but it's true for Stack<T>; see Hans Passant's excellent answer for the reason why.
You had me going there for a bit, that indeed looks completely bass-ackwards. There is however something else going on. The Stack<> class has a debugger visualizer, named System_StackDebugView<>. It is an internal class, you'd have to look with Reflector to see it.
That visualizer has an Items property, that's what you look at when you expand the node in the debugger. That Items property uses Stack<>.ToArray(). Which looks like this:
public T[] ToArray()
{
T[] localArray = new T[this._size];
for (int i = 0; i < this._size; i++)
{
localArray[i] = this._array[(this._size - i) - 1];
}
return localArray;
}
Yup, backwards.
What you described is the correct implementation, as a stack is a LIFO (Last in First out) structure. Imagine it like a stack of plates, the most recently element placed into the stack is the first one removed. Have you run into a stack elsewhere that is FIFO?
FIFO would be a Queue.
Here is how the stack's push and pops methods are implemented. Notice that it is using the last index in the array, rather than the first. So there must be some other problem going on to get yours backwards.
public virtual void Push(object obj)
{
if (this._size == this._array.Length)
{
object[] destinationArray = new object[2 * this._array.Length];
Array.Copy(this._array, 0, destinationArray, 0, this._size);
this._array = destinationArray;
}
this._array[this._size++] = obj;
this._version++;
}
public virtual object Pop()
{
if (this._size == 0)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
}
this._version++;
object obj2 = this._array[--this._size];
this._array[this._size] = null;
return obj2;
}
To add to the other answers, if in the debugger you scroll down to the bottom of your Stack<>'s elements and open up Raw View->Non-Public members->_array you can see the contents of the actual internal array used to hold the items and verify that they are in the expected order.
I don't see what it matters which end they consider the top of the stack, as long as you now know which end it is. It actually makes more sense that when you 'push' something on to the stack, you're pushing it on the top (beginning) and moving the other items down...

Categories