]> git.sesse.net Git - stockfish/blobdiff - src/thread.cpp
Fix uninitialized memory usage
[stockfish] / src / thread.cpp
index d358dec3f5b2da4f2644e4759b8269dd0855eeab..d095aefeb6a6f875746a67ab68d782e32d031e28 100644 (file)
@@ -35,6 +35,7 @@ ThreadPool Threads; // Global object
 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
 
   wait_for_search_finished();
+  clear(); // Zero-init histories (based on std::array)
 }
 
 
@@ -51,6 +52,20 @@ Thread::~Thread() {
 }
 
 
+/// Thread::clear() reset histories, usually before a new game
+
+void Thread::clear() {
+
+  counterMoves.fill(MOVE_NONE);
+  mainHistory.fill(0);
+
+  for (auto& to : contHistory)
+      for (auto& h : to)
+          h.fill(0);
+
+  contHistory[NO_PIECE][0].fill(Search::CounterMovePruneThreshold - 1);
+}
+
 /// Thread::start_searching() wakes up the thread that will start the search
 
 void Thread::start_searching() {
@@ -158,10 +173,12 @@ void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
   if (states.get())
       setupStates = std::move(states); // Ownership transfer, states is now empty
 
-  // We use Position::set() to set root position across threads. So we
-  // need to save and later to restore st->previous, cleared by set().
-  // Note that setupStates is shared by threads but is accessed in read-only mode.
-  StateInfo* previous = setupStates->back().previous;
+  // We use Position::set() to set root position across threads. But there are
+  // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
+  // be deduced from a fen string, so set() clears them and to not lose the info
+  // we need to backup and later restore setupStates->back(). Note that setupStates
+  // is shared by threads but is accessed in read-only mode.
+  StateInfo tmp = setupStates->back();
 
   for (Thread* th : Threads)
   {
@@ -171,7 +188,7 @@ void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
       th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
   }
 
-  setupStates->back().previous = previous;
+  setupStates->back() = tmp;
 
   main()->start_searching();
 }