Skip to content

Segfault while exiting when both cursor/connection are left unclosed #131

@bewithgaurav

Description

@bewithgaurav

Describe the bug

Observed a segmentation fault (crash) when Python exits after using the mssql_python.Connection and mssql_python.Cursor objects. The issue typically occurred when one or more cursors were still alive or not explicitly closed before the connection was garbage collected or when the interpreter was shutting down.

Steps to Reproduce

  • Open a connection using connect(conn_str).
  • Create one or more cursors from the connection.
  • Execute simple queries on these cursors (e.g., cursor.execute("SELECT 1") and cursor.fetchall()).
  • Do not explicitly close all cursors or the connection.
  • Allow the program to exit or forcibly trigger garbage collection (e.g., using del and gc.collect()).

Example code that triggers the issue:

from mssql_python import connect
conn = connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT 1")
cursor.fetchall()
# Do not close cursor or connection
# Exit Python or run: del conn; import gc; gc.collect()

Expected behavior

Python process should exit cleanly without any crash, even if cursors/connections are not explicitly closed.

Actual Behavior
A segmentation fault may occur at interpreter shutdown, likely due to the order in which destructors (del methods) attempt to clean up underlying database resources.

Root Cause
The bug was caused by improper cleanup order and reference handling between Connection and Cursor objects. If the connection was destroyed before its cursors, or if garbage collection occurred out of order, attempts to free resources could lead to undefined behavior and a segfault.

Further technical details

Python version: All supported
SQL Server version: All supported
Operating system: All supported

Additional context
ADO Task - AB#37889
Add any other context about the problem here.

Metadata

Metadata

Assignees

Labels

Triage DoneIssues that are triaged by dev team and are in investigation.

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions