Files
pybind11/tests/test_iostream.py
Agis Kounelis 7029f99cc6 fix: segfault when moving scoped_ostream_redirect (#6033)
* fix: segfault when moving `scoped_ostream_redirect`

The default move constructor left the stream (`std::cout`) pointing at
the moved-from `pythonbuf`, whose internal buffer and streambuf pointers
were nulled by the move. Any subsequent write through the stream
dereferenced null, causing a segfault.

Replace `= default` with an explicit move constructor that re-points
the stream to the new buffer and disarms the moved-from destructor.

* fix: mark move constructor noexcept to satisfy clang-tidy

* fix: use bool flag instead of nullptr sentinel for moved-from state

Using `old == nullptr` as the moved-from sentinel was incorrect because
nullptr is a valid original rdbuf() value (e.g. `std::ostream os(nullptr)`).
Replace with an explicit `active` flag so the destructor correctly
restores nullptr buffers.

Add tests for the nullptr-rdbuf edge case.

* fix: remove noexcept and propagate active flag from source

- Remove noexcept: pythonbuf inherits from std::streambuf whose move
  is not guaranteed nothrow on all implementations. Suppress clang-tidy
  with NOLINTNEXTLINE instead.
- Initialize active from other.active so that moving an already
  moved-from object does not incorrectly re-activate the redirect.
- Only rebind the stream and disarm the source when active.

* test: add unflushed ostream redirect regression

Cover the buffered-before-move case for `scoped_ostream_redirect`, which still crashes despite the current move fix. This gives the PR a direct reproducer for the remaining bug path.

Made-with: Cursor

* fix: disarm moved-from pythonbuf after redirect move

The redirect guard now survives moves, but buffered output could still remain in the moved-from `pythonbuf` and be flushed during destruction through moved-out Python handles. Rebuild the destination put area from the transferred storage and clear the source put area so unflushed bytes follow the active redirect instead of crashing in the moved-from destructor.

Made-with: Cursor

---------

Co-authored-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
2026-04-15 21:08:06 -07:00

8.0 KiB