使用 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 bymsg
to represent the content referenced by thebuffer
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 tozmq_msg_init_data()
.Never access
zmq_msg_t
members directly, instead always use thezmq_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/