io0000
io0000

Reputation: 1

Does libuv cause memory leak in uv_listen()?

I test my small program that uses libuv.

Program's debug output shows memory leak.

condition

libuv version

#define UV_VERSION_MAJOR 0
#define UV_VERSION_MINOR 9

my test code

#include "stdafx.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crtdbg.h>
#include <conio.h>
#include <uv.h>

void on_new_connection(uv_stream_t *server, int status) {
}

int main() 
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    uv_tcp_t server;
    uv_tcp_init(uv_default_loop(), &server);

    struct sockaddr_in bind_addr = uv_ip4_addr("0.0.0.0", 9123);
    uv_tcp_bind(&server, bind_addr);

    // leak occurred here  
    uv_listen((uv_stream_t*)&server, 128, on_new_connection);   

    //uv_close((uv_handle_t*)&server, NULL);
    return 0;
}

result

Detected memory leaks!
Dumping objects ->
{56} normal block at 0x002A3258, 11136 bytes long.
Data: <T B             > 54 F8 42 00 09 00 00 00 CD CD CD CD CD CD CD CD 
Object dump complete.

internal leak location

call stack

uv_tcp_listen(...) 
uv_listen(...)
main(...)  

code

uv_tcp_listen(...)
{
  ....
  if(!handle->accept_reqs) {
    handle->accept_reqs = (uv_tcp_accept_t*)
      malloc(uv_simultaneous_server_accepts * sizeof(uv_tcp_accept_t));  << 
  ....
}

Upvotes: 0

Views: 1051

Answers (2)

Tanner Sansbury
Tanner Sansbury

Reputation: 51951

With proper cleanup, uv_listen should not leak memory. In this case, uv_close needs to be invoked, and the default loop needs to run to completion.

Calling uv_close will place the server into a closing state. Once there are no more pending operations, an endgame is added to the loop for deferred invocation. The endgame will be processed within uv_run, which will eventually free accept_reqs in uv_tcp_endgame.

Upvotes: 1

Someone
Someone

Reputation: 845

uv_listen() indeed calls malloc() but it's not a leak. However if you close the server handle (and wait for the close callback) the memory will be freed again.

Upvotes: 1

Related Questions