CodexBloom - Programming Q&A Platform

C++20 coroutines causing stack overflow when using co_await with large data structures

👀 Views: 73 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-06
c++20 coroutines async performance C++

I'm maintaining legacy code that I've been struggling with this for a few days now and could really use some help. I've been struggling with this for a few days now and could really use some help. I'm working with a stack overflow behavior when using C++20 coroutines with `co_await` on large data structures. The coroutine fetches a large vector of data from a database asynchronously, but when I try to `co_await` the operation, it seems to exceed the stack size. Here's a simplified version of what I'm doing: ```cpp #include <coroutine> #include <iostream> #include <vector> #include <thread> struct Awaitable { bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> handle) { std::thread([handle]() { handle.resume(); }).detach(); } std::vector<int> await_resume() { // Simulate fetching a large vector std::vector<int> data(1000000, 42); return data; } }; co_await Awaitable(); int main() { std::cout << "Starting coroutine...\n"; // Coroutine logic here return 0; } ``` I have tried increasing the stack size with `_set_stack_size` on Windows, but it still doesn't resolve the scenario. I suspect that the coroutine's internal state might be too large, causing the stack to overflow when the return type is a large vector. I also tried changing the return type to be a `std::shared_ptr<std::vector<int>>` instead, which alleviates the question somewhat, but it still doesn't feel right. I'm unsure if I'm misusing coroutines or if there's an inherent limitation here. Has anyone else experienced this or have suggestions on how to handle large data structures with coroutines effectively? Any insights on best practices would be appreciated. What's the best practice here? I'd really appreciate any guidance on this. What's the correct way to implement this?