Search code examples
clibuv

libuv read callback uv_buf_t cleanup


The signature of the libuv read completion callback is:

void (*uv_read_cb)(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)

My understanding from the documentation is that my callback is responsible for freeing the base member of the supplied uv_buf_t*. My question is - who is responsible for freeing the memory pointed to by buf?


Solution

  • Consider the internal function uv__read. This is where your callback is invoked (set aside uv__stream_eof that isn't of much interest for this Q/A).
    As you can see at the very first line of the function, the buffer is declared and defined as a local variable:

    uv_buf_t buf;
    

    If you go over the entire function, you can see that the same buffer is used with uv_buf_init and then passed to your callback (see here, here, here, here, here and here if you want more details). So, back to the question:

    who is responsible for freeing the memory pointed to by buf?

    Neither you nor libuv. The buffer is automatically freed when it goes out of scope. You have not to care about that and the documentation is clear: your sole responsibility is for the base data member.