我有一个unix_socket
类作为属性double*
,并在其构造函数中分配带new
的内存:
class unix_socket::unix_socket(){
//...
array_recvd=new double[10];
//...
}
因此我在析构函数中使用delete[]
来释放内存:
unix_socket::~unix_socket(){
//..
delete[] array_recvd;
//...
}
但是,当使用Valgrind
检查程序中的内存泄漏时,数组使用的内存不会被释放:
==4683== HEAP SUMMARY:
==4683== in use at exit: 80 bytes in 1 blocks
==4683== total heap usage: 2 allocs, 1 frees, 648 bytes allocated
==4683==
==4683== Searching for pointers to 1 not-freed blocks
==4683== Checked 188,184 bytes
==4683==
==4683== 80 bytes in 1 blocks are still reachable in loss record 1 of 1
==4683== at 0x4C2BBA4: operator new[](unsigned long) (vg_replace_malloc.c:363)
==4683== by 0x406503: unix_socket::unix_socket() (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/client)
==4683== by 0x402355: main (in /home/joao/CloudPT/Bolsa/Webots/controllers/darwin-pi2/client)
==4683==
==4683== LEAK SUMMARY:
==4683== definitely lost: 0 bytes in 0 blocks
==4683== indirectly lost: 0 bytes in 0 blocks
==4683== possibly lost: 0 bytes in 0 blocks
==4683== still reachable: 80 bytes in 1 blocks
==4683== suppressed: 0 bytes in 0 blocks
我确定这个泄漏是由 vector_recvd
array_recvd
引起的,因为只有在我将它作为属性时才会出现。我究竟做错了什么?我如何释放双打数组分配的内存?
编辑:这是我用来复制此问题的main.cpp
:
int main () {
unix_socket client;
client.initSocket(DEFAULT_SOCKET_PATH,CLIENT_MODE);
for (int i = 0; i < 100; ++i){
client.sendVectorXd(VectorXd::Ones(30));
}
client.closeSocket();
return 0;
}
可能相关:此问题仅在拒绝套接字连接时出现(没有服务器等待客户端)。
编辑2 :所以我发现了问题,确实在initSocket()
。如果以某种方式连接到套接字服务器失败(就像这样),我有exit(1)
:
if (connect(client_sock, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
我认为调用exit()
会调用析构函数,我现在看到的情况并非如此。