c - c中zmq客户端内存泄漏

标签 c zeromq

使用 valgrind 运行的 zmq 客户端内存泄漏 代码:

#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 日志:

==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

为什么运行时可能会出现漏失现象?请帮忙解决同样的问题。

最佳答案

古老而良好的 ZeroMQ 实践对资源非常谨慎:

处理消息(和隐藏的数据结构)需要谨慎:

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

应该“表现良好”。

为什么?请仔细阅读 API 规范:

如果编译了不合规的用例,则会在以下位置明确警告泄漏:

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.

关于c - c中zmq客户端内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45789252/

相关文章:

python - Zeromq (pyzmq) ROUTER处理多个客户端的数据以及后续的超时处理

关于 C 中位域排序语义的说明

c - 恼人的 strcat() 输出

c++ - 如何从 C++ 中的 .recv() 和 .send() 方法读取 ZeroMQ 返回值?

python - Threading Condition Acquire lock 并不是真正获取锁

java - java应用程序中的zeroMQ UnsatisfiedLinkError

C++ protobuf,ZMQ。客户端-服务器接口(interface)的功能

c++ - char 的实习工作 - 更好/等于查找

c - 从数组中读取两个字符作为C中的一个十六进制数

c - 向我的简单 shell 添加历史功能