I was implementing a chess bot in c++ using recursive algorithms and the program evaluates over a million nodes per move.
Over time the memory it takes up gets to over 1 GIG of RAM…
But I don’t really need the variables that were previously declared after I’m done with the move…
So how do I manually flush the stack memory to get rid of the previously declared variables on the stack just like java’s garbage collector?
UPDATE
I found out that there’s this line in my source:
Move * M = new Move(x1,y1,x2,y2);
pair <Move *, Piece *> pr (M,aPiece);
and it’s in the perform move function which gets called a million times in the recursion…
My question is, how would you clear such variable once all the recursion is done and I no longer need this variable, but while the recursion is doing its thing, I need that variable to stay in the memory?
Stack-based storage is reclaimed as soon as the function call in which it resides returns.
Is it possible that you were using heap-allocated memory (i.e. calling
new) within your recursive function? Alternatively, if you’re simply looking at the Windows Task Manager or an equivalent, you may be seeing “peak” usage, or seeing some delay between memory being freed by your program and returned to the OS memory pool.Follow up (after question was edited):
It’s not clear what you are doing with the
pair<Move*, Piece*>, so I can’t tell if the Move objects need to be held by pointer or not. The primary reasons for holding them via pointer would be polymorphism (not used here since you don’t appear to be creating subclass objects) and to allow their lifetime to be independent of the call stack. Sounds like you don’t have that reason, either. So, why not: