Skip to content

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

Description

@dongyaosheng
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<void> and then co_await-ed, the code runs without issues.

Code (simplified)

Version that crashes

boost::cobalt::task<void> session::writer_loop_impl()
{
    auto timer = std::make_shared<boost::asio::steady_timer>(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<std::vector<uint8_t>> data = msg->serialize();
            if (!data) continue;

            uint32_t length = static_cast<uint32_t>(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<void> session::writer_loop_impl()
{
    // ... same setup ...
    while (running_.load())
    {
        try
        {
            // ... same message handling ...

            auto func = [data, this]() -> boost::cobalt::task<void>
            {
                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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions