boostorg / boostorg/cobalt

# Writer loop crashes when directly `co_await` write, but works when wrapped in lambda

Open
#268 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
347
Forks
47
Avg merge
3d 8h
Merged PRs (30d)
1

Description

Image
# Writer loop crashes when directly `co_await` write, but works when wrapped in lambda

## Description
In a `boost::cobalt` based writer loop, directly `co_await`-ing a `boost::cobalt::io::write` operation leads to a crash (possibly stack corruption). However, if the write operation is wrapped in a lambda that returns a `cobalt::task` and then `co_await`-ed, the code runs without issues.

## Code (simplified)

### Version that crashes
```cpp
boost::cobalt::task session::writer_loop_impl()
{
auto timer = std::make_shared(co_await boost::cobalt::this_coro::executor);
while (running_.load())
{
try
{
auto msg = co_await send_channel_.async_receive(boost::cobalt::use_op);
if (!msg) continue;

std::shared_ptr> data = msg->serialize();
if (!data) continue;

uint32_t length = static_cast(data->size());
auto length_array = convertToHostByteArray(length);
data->insert(data->begin(), length_array.begin(), length_array.end());

// Direct co_await - crashes
co_await boost::cobalt::io::write(*stream_, boost::asio::buffer(*data));
}
catch (const std::exception& e)
{
LOG_ERROR("Writer loop error: {}", e.what());
co_return;
}
}
co_return;
}

Version that works
cpp
boost::cobalt::task session::writer_loop_impl()
{
// ... same setup ...
while (running_.load())
{
try
{
// ... same message handling ...

auto func = [data, this]() -> boost::cobalt::task
{
co_await boost::cobalt::io::write(*stream_, boost::asio::buffer(*data));
};

// Wrapped in lambda - works
co_await func();
}
catch (const std::exception& e)
{
LOG_ERROR("Writer loop error: {}", e.what());
co_return;
}
}
co_return;
}
Environment
OS: [e.g., Windows 10]

Compiler: [e.g., MSVC 2022]

Boost version: [e.g., 1.90.0]

Build type: Debug

C++ standard: C++20 (with coroutine support enabled)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.