Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Lib/test/test_os/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,18 @@ def test_clearenv(self):

self.assertRaises(TypeError, os.environ.clear, None)

def test_clearenv_environ_not_null(self):
Comment thread
search1ofall-maker marked this conversation as resolved.
import ctypes
Comment thread
aisk marked this conversation as resolved.
Outdated
os.environ.clear()
try:
c_environ = ctypes.c_void_p.in_dll(ctypes.CDLL(None), "environ")
self.assertIsNotNone(
c_environ.value,
"os.environ.clear() set the C 'environ' pointer to NULL"
)
except AttributeError:
Comment thread
aisk marked this conversation as resolved.
Outdated
pass


class WalkTests(unittest.TestCase):
"""Tests for os.walk()."""
Expand Down
1 change: 1 addition & 0 deletions Misc/NEWS.d/next/Library/2026-09-18-15-30-00.GH-157741.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix crash in third-party C libraries (such as Tcl/Tk) after :func:`os.environ.clear` by ensuring the C ``environ`` pointer is not left as ``NULL``.
9 changes: 8 additions & 1 deletion Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -13893,7 +13893,8 @@ os_unsetenv_impl(PyObject *module, PyObject *name)
}
#endif /* !MS_WINDOWS */


static char *empty_environ[] = { NULL };
Comment thread
aisk marked this conversation as resolved.
Outdated
/*NR8889*/
Comment thread
aisk marked this conversation as resolved.
Outdated
#ifdef HAVE_CLEARENV
/*[clinic input]
os._clearenv
Expand All @@ -13912,6 +13913,12 @@ os__clearenv_impl(PyObject *module)
if (err) {
return posix_error();
}

/* glibc's clearenv() sets 'environ' to NULL. Point it to a static empty
array to prevent crashes in third-party C libraries (e.g. Tcl/Tk)
that access 'environ' without a NULL check. */
environ = empty_environ;

Py_RETURN_NONE;
}
#endif
Expand Down
Loading