Skip to content

Commit b25312e

Browse files
committed
ExecutionContext: Add clearStringStack() method
1 parent 2bac780 commit b25312e

2 files changed

Lines changed: 17 additions & 7 deletions

File tree

‎include/scratchcpp/executioncontext.h‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class LIBSCRATCHCPP_EXPORT ExecutionContext
4141

4242
inline StringPtr **pushStringStack(size_t stringCount)
4343
{
44+
m_stringStackCleared = false;
4445
m_stringStack.push({});
4546

4647
auto &strings = m_stringStack.top();
@@ -55,7 +56,11 @@ class LIBSCRATCHCPP_EXPORT ExecutionContext
5556

5657
inline void popStringStack()
5758
{
58-
assert(!m_stringStack.empty());
59+
if (m_stringStackCleared) // avoid UB when popping after killing a thread
60+
return;
61+
62+
assert(!m_stringStack.empty()); // check only in debug mode to maximize performance
63+
5964
const auto &strings = m_stringStack.top();
6065

6166
for (StringPtr *str : strings)
@@ -64,10 +69,20 @@ class LIBSCRATCHCPP_EXPORT ExecutionContext
6469
m_stringStack.pop();
6570
}
6671

72+
inline void clearStringStack()
73+
{
74+
while (!m_stringStack.empty()) {
75+
popStringStack();
76+
}
77+
78+
m_stringStackCleared = true;
79+
}
80+
6781
private:
6882
spimpl::unique_impl_ptr<ExecutionContextPrivate> impl;
6983

7084
std::stack<std::vector<StringPtr *>> m_stringStack;
85+
bool m_stringStackCleared = false;
7186
};
7287

7388
} // namespace libscratchcpp

‎src/engine/executioncontext.cpp‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,7 @@ ExecutionContext::ExecutionContext(Thread *thread) :
1717
ExecutionContext::~ExecutionContext()
1818
{
1919
// Deallocate strings
20-
// NOTE: The stack should be already empty
21-
assert(m_stringStack.empty());
22-
23-
while (!m_stringStack.empty()) {
24-
popStringStack();
25-
}
20+
clearStringStack();
2621
}
2722

2823
/*! Returns the thread of this context. */

0 commit comments

Comments
 (0)