Wednesday, April 21, 2010

Memory leak management while using apache libraries

   I had faced a memory leak  issue when using apache APIs to create sockets. My application designs to monitor some set of ports continuously in a frequent time span. Application internally uses APIs from apache library to create memory pool, to create sockets, to shutdown socket etc..
First, it will create a pool of memory by using apr_pool_create function as below .
apr_pool_create(&newPool, NULL)

And then it makes a socket address with apr_sockaddr_info_get call as below.
//making socket address
apr_sockaddr_info_get(&remote_sa, dest, APR_UNSPEC,
(apr_uint16_t)portNum, 0, pool)

Then it creates a Socket as below.
apr_socket_create(&sock, remote_sa->family,
After creating socket, it tries binds to the port.
apr_bind(sock, remote_sa)
Then connect to the port and started listening for a connection request.
apr_connect(sock, remote_sa)

And then below functions are used for other usual socket activities.
apr_recv(sock, dataRecv, &length);

After the socket's tasks finished, we used to shutdown the socket and close for further actions.
apr_shutdown(sock, APR_SHUTDOWN_WRITE)

These all above code works in a while(1) loop. Creation of memory pool is a one time activity. Remaining tasks(from socket creation to socket closing) are continuously looped until application killed.
This application will be working as a process, which always present in active memory to listen the specified ports. I have received an issue from one of our customer saying that, he is observing a memory leak while running this process. I took this task and me too observed the same issue in my development server.
In general, reproducing a problem is the 60% of the solution. But, in memory leak problem, it will be only 40%. You may observe a leak, but you may not come to a conclusion that, this leak is happened by this reason.
I did a regular memory leak check up in the big code base. I searched from malloc, realloc, calloc etc. And I searched for any macros defined against malloc.

Nothing!!! No memory allocation calls used in the code. Then my spy glass went the the pool creation API (apr_pool_create). I observed that Memory pool is created but not freed any where. I have Apache API to delete the pool. But, if I delete the pool, application will be killed immediately. I wanted to retain my application in active memory unless, user forcefully killed him.

So I cant use apr_pool_destroy to release the memory pool. Then i visited Apache Portability Runtime library for the API reference . I found there is another call apr_pool_clear(pool) to clear the memory location. GOD GRACE. I did that !!!.
My issue is resolved. So whenever a new socket finished his tasks, he will clear the pool and return the handler to begin. And then new socket will allocate the memory from free pool. Hence no memory leak !!!