From 97ae015fb7bb724239769d34c4d1df7a7810b5c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E8=8A=B7=E9=85=B1=E7=B4=AB?= Date: Tue, 3 Mar 2026 16:44:04 +0800 Subject: [PATCH] Harden Search::Do state transitions to avoid crashes --- ZACLib/ZACLib.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/ZACLib/ZACLib.cpp b/ZACLib/ZACLib.cpp index 5e091a5..045c102 100644 --- a/ZACLib/ZACLib.cpp +++ b/ZACLib/ZACLib.cpp @@ -218,10 +218,23 @@ namespace ZACLib { std::vector Search::Do(const ZAC_SV& input) const { std::vector result; + if (trie.empty()) return result; + int state = 0; for (size_t i = 0; i < input.size(); ++i) { const auto c = static_cast(input[i]); - state = trie[state].next[c]; + + // Allow matching even when Build() has not been called yet. + // In that case transitions can still be -1, so we fall back to + // the fail chain and finally the root instead of indexing trie[-1]. + while (state != 0 && trie[state].next[c] == -1) { + state = trie[state].fail; + } + if (trie[state].next[c] != -1) { + state = trie[state].next[c]; + } else { + state = 0; + } if (trie[state].output_id != Node::kInvalidOutput) { result.push_back(