skypjack skypjack - 1 month ago 9
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_init
:

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
base
can be freed immediately after a call to
uv_buf_init
.

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

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
    uv_try_write
    or the other
    *_write
    functions is done instead? That is, once the data have been actually consumed indeed.


Answer

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`.