Parvathy K
Parvathy K

Reputation: 79

Memory leakage in zmq client in c

Memory Leakage in zmq client running using valgrind Code:

#include<stdio.h>
#include<stdlib.h>
#include<zmq.h>
#include<unistd.h>
#include<string.h>
#include <signal.h>
volatile sig_atomic_t stop;
void inthand(int signum) {
    stop = 1;
}
int main(){
        signal(SIGINT, inthand);
        char buffer[1024];
        int i=0;
        void *context = zmq_ctx_new();
        void *request = zmq_socket(context, ZMQ_REQ);
        zmq_connect(request,"tcp://10.30.11.215:2424");
        while(!stop){
                memset(buffer,0,1024);
                zmq_send(request,"HELLO",5,0);
                zmq_recv(request,buffer,sizeof(buffer),0);
        }
        zmq_close(request);
        zmq_ctx_destroy(context);
}

valgrind log:

==19532== HEAP SUMMARY:
==19532==     in use at exit: 36,678 bytes in 43 blocks
==19532==   total heap usage: 236 allocs, 193 frees, 138,270 bytes allocated
==19532== 
==19532== LEAK SUMMARY:
==19532==    definitely lost: 0 bytes in 0 blocks
==19532==    indirectly lost: 0 bytes in 0 blocks
==19532==      possibly lost: 36,318 bytes in 38 blocks
==19532==    still reachable: 360 bytes in 5 blocks
==19532==         suppressed: 0 bytes in 0 blocks
==19532== Rerun with --leak-check=full to see details of leaked memory

why possibly lost leakage occur while running? Please help to solve the same.

Upvotes: 0

Views: 1515

Answers (1)

user3666197
user3666197

Reputation: 1

Old and good ZeroMQ practice was carefull wrt resources:

A due care was expected to handle messages ( and hidden data-structures ):

zmq_msg_t            aMessage;
zmq_msg_init_size ( &aMessage,  1024 );
zmq_msg_data      ( &aMessage, "HELLO", 5 );
...
zmq_msg_close     ( &aMessage );

ought take place to "behave well".

Why? Just read the API-specification with due care:

If non-compliant use-cases are compiled, the leaks were explicitly warned about in:

The zmq_msg_init_data() function shall initialise the message object referenced by msg to represent the content referenced by the buffer located at address data, size bytes long. No copy of data shall be performed and ØMQ shall take ownership of the supplied buffer.

If provided, the deallocation function ffn shall be called once the data buffer is no longer required by ØMQ, with the data and hint arguments supplied to zmq_msg_init_data().

Never access zmq_msg_t members directly, instead always use the zmq_msg family of functions.

The deallocation function ffn needs to be thread-safe, since it will be called from an arbitrary thread.

If the deallocation function is not provided, the allocated memory will not be freed, and this may cause a memory leak.

Upvotes: 1

Related Questions