Skip to content

LRUCache: make insert() more robust against duplicate keys#130

Open
ashie wants to merge 1 commit into
fcitx:masterfrom
clear-code:fix-potential-crash
Open

LRUCache: make insert() more robust against duplicate keys#130
ashie wants to merge 1 commit into
fcitx:masterfrom
clear-code:fix-potential-crash

Conversation

@ashie

@ashie ashie commented Jun 10, 2026

Copy link
Copy Markdown

While debugging a crash in libime 1.0.7, I noticed a corner case in LRUCache::insert() that may be worth discussing.

The cache returns nullptr when the key already exists. Some call sites appear to assume that insert() always returns a valid pointer and immediately dereference the result. In my case this eventually led to a crash while entering pinyin text.

I was only able to reproduce the problem on libime 1.0.7. After upgrading to libime 1.0.17, I could no longer reproduce the original crash, so this may already be fixed indirectly by other changes.

The attached patch changes insert() to return the existing entry when the key is already present, adds a guard for zero-capacity caches, and adds a sanity check in evict().

I cannot say that this is the root cause of the issue. However, the patch applies cleanly to current master and makes the cache API more defensive against accidental misuse.

Please feel free to close this PR if the current behavior is intentional or if there is already a preferred solution. I mainly wanted to share the findings from the investigation in case they are useful.

LRUCache::insert() returned nullptr when the key already existed in
the cache. Some callers assumed that a prior find() guaranteed that
insert() would always succeed, which could lead to nullptr dereference
and crashes during pinyin matching.

Update insert() to return the existing value for duplicate keys
instead of returning nullptr. Also add handling for zero-capacity
caches and assert that eviction is never attempted on an empty list.

Additionally, add a defensive nullptr check in
PinyinDictionaryPrivate::matchWordsForOnePath() to avoid crashing
if insert() unexpectedly fails.

This fixes crashes observed during incremental pinyin input such as
typing "nih".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant