fix: guard LRUCache against non-positive capacity - #1749
Open
nikolauspschuetz wants to merge 1 commit into
Open
Conversation
NewLRUCache and NewSyncLRUCache are exported, but calling Put on a cache created with a non-positive capacity panicked with a nil pointer dereference: the eviction path removes cache.tail.prev, which on an empty list is the head sentinel whose prev pointer is nil. Return early from Put when capacity is non-positive, since such a cache holds nothing. Add a regression test that fails (panics) before this change and passes after.
nikolauspschuetz
marked this pull request as ready for review
August 16, 2026 15:12
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
NewLRUCacheandNewSyncLRUCacheare exported public API, but callingPuton a cache created with a non-positive capacity panics with a nil pointer dereference.Reproduce:
On the first insert, the eviction branch is taken (
len(cache.m) >= cache.capacityis0 >= 0), which callscache.remove(cache.tail.prev, false). On an empty listcache.tail.previs theheadsentinel, whoseprevisnil, soremovedereferencesnilatutil/util.go.Fix
Return early from
Putwhencapacity <= 0— such a cache holds nothing, so there is nothing to store and no eviction to perform. This keepsGetreturning(nil, false)for every key, consistent with a zero-capacity cache.Guarding the eviction path instead would let a zero-capacity cache incorrectly hold one entry, so the early return is the more correct minimal fix.
Test
Added
TestLRUCacheNonPositiveCapacityinutil/util_test.go. It panics onmasterand passes with this change:panic: runtime error: invalid memory address or nil pointer dereference(inPut)ok github.com/casbin/casbin/v3/utilfor the record: fix found and drafted with AI assistance; reviewed and verified by me.