newbie question: uv_close and free the memory of the handle

Skip to first unread message

Ariel Machado

Jul 6, 2020, 2:11:45 PM7/6/20
to libuv
Hi folks, newbie question about memory managment with uv handles:

For network handles, like uv_tcp_t, is it safe to free the memory immediately after calling uv_close () and not waiting for the callback?


uv_close (handle, NULL);
uv_close (handle, close_done_cb);
(uv_handle_t * handle) {

According the documentation:
void uv_close(uv_handle_t* handle, uv_close_cb close_cb)

Request handle to be closed. close_cb will be called asynchronously after this call. This MUST be called on each handle before memory is released. Moreover, the memory can only be released in close_cb or after it has returned.

Handles that wrap file descriptors are closed immediately but close_cb will still be deferred to the next iteration of the event loop. It gives you a chance to free up any resources associated with the handle.

but I've seen a lot of C ++ examples where uv_tcp_init() is placed in the class constructor and uv_close() in the class destructor, which leaves me a bit confused, if this RAII approach is introducing a problem, or is taking advantage that the socket is a file descriptor, so the closing of this kind of  handles are closed when invoking uv_close.

I'm trying to understand how to correctly create classes and instantiate and destroy objects that internally manage uv_handle_t with their asynchronous approach.


Iñaki Baz Castillo

Jul 6, 2020, 2:24:32 PM7/6/20
No. You must always wait for the close cb before you free memory.

You received this message because you are subscribed to the Google Groups "libuv" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit
Reply all
Reply to author
0 new messages