Skip to content

Fix reference leak in pyodbc.dataSources() (#1502) - #1504

Merged
mkleehammer merged 1 commit into
mkleehammer:masterfrom
apoorvdarshan:fix-1502-datasources-leak
Nov 5, 2026
Merged

mkleehammer merged 1 commit into
mkleehammer:masterfrom
apoorvdarshan:fix-1502-datasources-leak

Conversation

@apoorvdarshan

Copy link
Copy Markdown
Contributor

Summary

Fixes #1502. mod_datasources() (backing pyodbc.dataSources()) builds each entry with PyUnicode_FromString(), which returns a new reference, and inserts it with PyDict_SetItem(), which does not steal references. The key/val strings were never released, so every entry leaks both strings on every call.

PyObject* key = PyUnicode_FromString((const char*)szDSN);
PyObject* val = PyUnicode_FromString((const char*)szDesc);
if(key && val)
    PyDict_SetItem(result, key, val);
// key and val leaked here

Fix

Py_XDECREF the key and val after inserting them (Py_XDECREF also handles the case where an allocation above failed). This matches the pattern already used elsewhere — e.g. cursor.cpp (Py_DECREF(index) after PyDict_SetItem) and pyodbcmodule.cpp:549 (Py_XDECREF(str) after PyDict_SetItem).

Verification

Built locally against unixODBC with three dummy DSNs configured, using sys.getallocatedblocks():

build allocated-block growth over 20 000 dataSources() calls
master 120001 (6 per call = 3 DSNs × key+val)
this PR 1 (~0)

pyodbc.dataSources() still returns the same dict of DSNs.

Disclosure: prepared with AI assistance; reviewed and verified locally.

mod_datasources() builds each result entry with PyUnicode_FromString(), which
returns a new reference, and adds it with PyDict_SetItem(), which does not
steal references. The key and value strings were never released, so every
entry returned by pyodbc.dataSources() leaked both strings on every call.

Py_XDECREF the key and value after inserting them, matching the pattern already
used elsewhere in the file (e.g. mod_wrap around PyDict_SetItem). Verified with
sys.getallocatedblocks(): a 3-DSN configuration leaked 6 blocks per call before
(120001 over 20000 calls) and ~0 after.

Fixes mkleehammer#1502.
@mkleehammer
mkleehammer merged commit 92daac3 into mkleehammer:master Nov 5, 2026
1 check passed
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.

Reference leak in pyodbc.dataSources()

2 participants