我有一个unix_socket
具有 adouble*
作为属性的类,并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()
会调用析构函数,我现在看到情况并非如此。