开发者

Unix socket: hostent makes memory leaks

开发者 https://www.devze.com 2022-12-15 06:53 出处:网络
I am writing client for TCP connection and conversion from IP to socket_addr makes memory leaks. There is following process:

I am writing client for TCP connection and conversion from IP to socket_addr makes memory leaks.

There is following process:

#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>

/** there is some code like method header etc. */

hostent * host = gethostbyaddr( ip, 4, AF_INET );开发者_C百科 // ip is char[4], I use IPv4

if ( !host ) return -2; // bad IP

netSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( netSocket == -1 ) return -3; // error during socket opening

sockaddr_in serverSock;
serverSock.sin_family = AF_INET;
serverSock.sin_port = htons( port );
memcpy( &( serverSock.sin_addr ), host->h_addr, host->h_length );

// and now there is function connect(...);

/** end of method */

This code works fine but when I tracked memory using I took 5 memory leaks. They are created by this line:

hostent * host = gethostbyaddr( ip, 4, AF_INET ); // ip is char[4], I use IPv4

I have tried delete it delete host; but this causes segmentation fault.

Do you have any ideas how I can clean the memory, please? This is my school project and we have to work with memory correctly.

EDIT: I am using Linux Ubuntu 9.04, g++ 4.3.3 and for memory testing mudflap library


You don't say what platform you are on, but typically the memory returned by gethostbyaddr will be allocated and managed by the sockets library you are using - you don't free it yourself. Whatever you are using to diagnose leaks is probably giveing false positives.

For example, this man page http://www.opengroup.org/onlinepubs/009695399/functions/gethostbyaddr.html says that the pointer returned may be to static data, while MS use thread local storage. In neither case can or should the data be freed, and in neither case is there a leak.


Try using getaddrinfo() and freeaddrinfo() as suggested by the manpage for gethostbyname.


Remarks from the Windows gethostbyaddr function remarks at MSDN:

An application should not try to release the memory used by the returned hostent structure. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the application should copy any information it needs before issuing any other function calls to gethostbyaddr or gethostbyname.


The hostent structure is allocated internally by the socket library and retained for reuse by subsequent calls. The memory is not being leaked even though, as you observed, it is not being released.

0

精彩评论

暂无评论...
验证码 换一张
取 消