Repository navigation
Conversation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
detail::OstreamRedirect::enter()runsredirect_stdout.reset(new scoped_ostream_redirect()). Calling__enter__a second time without an__exit__in between (nesting the sameostream_redirectcontext manager) constructs the replacement beforereset()destroys the current one, so the newscoped_ostream_redirectrecordsstd::cout.rdbuf()while that still points at the buffer owned by the redirectreset()is about to delete. After the delete the live redirect holds a danglingoldstreambuf, and on__exit__its destructor restoresstd::cout/std::cerrto that freed buffer. The next write to the stream dereferences freed memory.Minimal repro, stdout only:
Releasing the existing redirect before constructing the replacement makes the new one capture the real original buffer, so no dangling pointer is left behind. Single enter/exit and sequential reuse of the same object are unaffected.
The added
test_redirect_reentrysegfaults on the current headers and passes with the fix.This fix was found and prepared with AI assistance and reviewed by me before submitting.
Suggested changelog entry:
py::add_ostream_redirectwhen the context manager's__enter__was entered again without an intervening__exit__.