Search code examples
c++windowssocketswinsockoverlapped-io

When using WSASend in overlapped mode, when should I free the buffers?


I am using WSASend() to send some data with IOCP. I allocate a buffer and fill it with data to send, then create a WSABUF pointing to my buffer and pass it into WSASend().

The documentation says:

If this function is completed in an overlapped manner, it is the Winsock service provider's responsibility to capture the WSABUF structures before returning from this call

So, I can stack-allocate my WSABUF structures. However, can I also locally allocate my underlying buffer, freeing it after WSASend() returns but before the IO finishes? Or should I transfer ownership of the underlying buffer to my IOCP worker thread so that it can free it?


Solution

  • can I also locally allocate my underlying buffer, freeing it after WSASend() returns but before the IO finishes?

    No. The buffer must remain allocated until after the IO is completely done using it. Only then can you free it.

    Or should I transfer ownership of the underlying buffer to my IOCP worker thread so that it can free it?

    Yes.