skypjack skypjack - 2 months ago 19
C Question

libuv and uv_buf_init: who should free what?

Consider the official documentation for libuv (section miscellaneous utilities).

This is the declaration of


uv_buf_t uv_buf_init(char* base, unsigned int len)

The documentation states that (emphasis mine):

Constructor for uv_buf_t.

Due to platform differences the user cannot rely on the ordering of the base and len members of the uv_buf_t struct. The user is responsible for freeing base after the uv_buf_t is done. Return struct passed by value.

It seems to me that
can be freed immediately after a call to

On the other side, a
structure is documented as composed by two fields:
, that has type
char *
, and
, that has type

What is not clear to me is:

  • Are data copied over into the buffer? (Well, I guess the answer is no, for it would be a great penalty in terms of performance).

  • Should I free the data once a call to
    or the other
    functions is done instead? That is, once the data have been actually consumed indeed.


Data are not copied over to the uv_buf_t, uv_buf_t.base refers to the same array of characters you used to create it.
Because of that, you have no performance penalties, but also you cannot drop the data immediately after the call to uv_buf_init.
Instead, you can free them once you have used the buffer, that is (as an example) when you have submitted it to uv_writeoruv_try_write`.