Skip to content

Commit 489cb84

Browse files
<syncstream>: fix std::osyncstream memory leak (microsoft#2763)
Co-authored-by: Stephan T. Lavavej <[email protected]>
1 parent 61d611b commit 489cb84

File tree

4 files changed

+35
-1
lines changed

4 files changed

+35
-1
lines changed

stl/inc/syncstream

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,11 +218,14 @@ protected:
218218
}
219219

220220
const _Size_type _New_capacity = _Calculate_growth(_Buf_size, _Buf_size + 1, _Max_allocation);
221-
const _Elem* const _Old_ptr = streambuf_type::pbase();
221+
_Elem* const _Old_ptr = streambuf_type::pbase();
222222
const _Size_type _Old_data_size = _Get_data_size();
223223

224224
_Elem* const _New_ptr = _Unfancy(_Al.allocate(_New_capacity));
225225
_Traits::copy(_New_ptr, _Old_ptr, _Old_data_size);
226+
if (0 < _Buf_size) {
227+
_Al.deallocate(_Refancy<_Pointer>(_Old_ptr), _Buf_size);
228+
}
226229

227230
streambuf_type::setp(_New_ptr, _New_ptr + _Old_data_size, _New_ptr + _New_capacity);
228231
streambuf_type::sputc(_Traits::to_char_type(_Current_elem));

tests/std/test.lst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ tests\GH_002558_format_presetPadding
205205
tests\GH_002581_common_reference_workaround
206206
tests\GH_002655_alternate_name_broke_linker
207207
tests\GH_002711_Zc_alignedNew-
208+
tests\GH_002760_syncstream_memory_leak
208209
tests\LWG2597_complex_branch_cut
209210
tests\LWG3018_shared_ptr_function
210211
tests\LWG3121_constrained_tuple_forwarding_ctor
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3+
4+
RUNALL_INCLUDE ..\usual_20_matrix.lst
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3+
4+
// REQUIRES: debug_CRT
5+
6+
#include <cassert>
7+
#include <cstdlib>
8+
#include <sstream>
9+
#include <syncstream>
10+
using namespace std;
11+
12+
// GH-2760, <syncstream>: std::osyncstream memory leak
13+
int main() {
14+
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
15+
[[maybe_unused]] _CrtMemState start;
16+
[[maybe_unused]] _CrtMemState end;
17+
[[maybe_unused]] _CrtMemState diff;
18+
_CrtMemCheckpoint(&start);
19+
{
20+
stringstream s;
21+
osyncstream bout(s);
22+
bout << "Hello, this line is long, which previously leaked memory" << '\n';
23+
}
24+
_CrtMemCheckpoint(&end);
25+
assert(_CrtMemDifference(&diff, &start, &end) == 0);
26+
}

0 commit comments

Comments
 (0)