Fix stack overflow when depth is too deep (#780)
authoryjf2002ghty <47345902+yjf2002ghty@users.noreply.github.com>
Mon, 29 Apr 2024 12:02:17 +0000 (20:02 +0800)
committerGitHub <noreply@github.com>
Mon, 29 Apr 2024 12:02:17 +0000 (14:02 +0200)
src/movegen.h
src/types.h

index bbb35b3..3047bf6 100644 (file)
@@ -55,12 +55,37 @@ inline bool operator<(const ExtMove& f, const ExtMove& s) {
 template<GenType>
 ExtMove* generate(const Position& pos, ExtMove* moveList);
 
+constexpr size_t moveListSize = sizeof(ExtMove) * MAX_MOVES;
+
 /// The MoveList struct is a simple wrapper around generate(). It sometimes comes
 /// in handy to use this class instead of the low level generate() function.
 template<GenType T>
 struct MoveList {
 
-  explicit MoveList(const Position& pos) : last(generate<T>(pos, moveList)) {}
+  
+#ifdef USE_HEAP_INSTEAD_OF_STACK_FOR_MOVE_LIST
+    explicit MoveList(const Position& pos)
+    {
+        this->moveList = (ExtMove*)malloc(moveListSize);
+        if (this->moveList == 0)
+        {
+            printf("Error: Failed to allocate memory in heap.");
+            exit(1);
+        }
+        this->last = generate<T>(pos, this->moveList);
+    }
+
+    ~MoveList()
+    {
+        free(this->moveList);
+    }
+#else
+    explicit MoveList(const Position& pos) : last(generate<T>(pos, moveList))
+    {
+        ;
+    }
+#endif
+  
   const ExtMove* begin() const { return moveList; }
   const ExtMove* end() const { return last; }
   size_t size() const { return last - moveList; }
@@ -69,7 +94,12 @@ struct MoveList {
   }
 
 private:
-  ExtMove moveList[MAX_MOVES], *last;
+    ExtMove* last;
+#ifdef USE_HEAP_INSTEAD_OF_STACK_FOR_MOVE_LIST
+    ExtMove* moveList = 0;
+#else
+    ExtMove moveList[MAX_MOVES];
+#endif
 };
 
 } // namespace Stockfish
index 5abfac8..b049736 100644 (file)
@@ -227,13 +227,22 @@ typedef uint64_t Bitboard;
 constexpr int SQUARE_BITS = 6;
 #endif
 
+//When defined, move list will be stored in heap. Delete this if you want to use stack to store move list. Using stack can cause overflow (Segmentation Fault) when the search is too deep.
+#define USE_HEAP_INSTEAD_OF_STACK_FOR_MOVE_LIST
+
 #ifdef ALLVARS
 constexpr int MAX_MOVES = 8192;
-constexpr int MAX_PLY   = 60;
+#ifdef USE_HEAP_INSTEAD_OF_STACK_FOR_MOVE_LIST
+constexpr int MAX_PLY = 246;
+#else
+constexpr int MAX_PLY = 60;
+#endif
+/// endif USE_HEAP_INSTEAD_OF_STACK_FOR_MOVE_LIST
 #else
 constexpr int MAX_MOVES = 1024;
-constexpr int MAX_PLY   = 246;
+constexpr int MAX_PLY = 246;
 #endif
+/// endif ALLVARS
 
 /// A move needs 16 bits to be stored
 ///