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 ); // 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.