Skip to content

Commit 81ca259

Browse files
committed
gh-157377: clamp gc.get_count() return value at zero
1 parent cb6cf50 commit 81ca259

2 files changed

Lines changed: 9 additions & 0 deletions

File tree

Lib/test/test_gc.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1658,6 +1658,12 @@ def test_indirect_calls_with_gc_disabled(self):
16581658
finally:
16591659
gc.enable()
16601660

1661+
def test_get_count_nonnegative(self):
1662+
xs = [[] for _ in range(1500)]
1663+
gc.collect()
1664+
del xs[:1000]
1665+
self.assertGreaterEqual(gc.get_count()[0], 0)
1666+
16611667
@gc_threshold(1000, 0, 0)
16621668
def test_get_count_does_not_prevent_collection(self):
16631669
junk = []

Modules/gcmodule.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,9 @@ gc_get_count_impl(PyObject *module)
224224
// Don't flush: record_allocation() checks the threshold only when it fills.
225225
int young = _Py_atomic_load_int_relaxed(&gcstate->young.count);
226226
young += (int)gc->alloc_count;
227+
if (young < 0) {
228+
young = 0;
229+
}
227230
#endif
228231

229232
#ifndef Py_GIL_DISABLED

0 commit comments

Comments
 (0)