I have this code right here to retrive the IP-address from a hostname:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils,
winsock;
function GetIPFromHost(const HostName: string): string;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
i: Integer;
begin
Result := '';
phe := GetHostByName(PChar(HostName));
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
i := 0;
while pPtr^[i] <> nil do
begin
Result := inet_ntoa(pptr^[i]^);
Inc(i);
end;
end;
var
wsaData: TWSAData;
begin
if (WSAStartup($0202, wsaData) <> 0) then begin
Exit;
end;
while true do begin
sleep (1000);
GetIPFromHost ('localhost');
end;
it works fine and gives me the IP address.
Unfortunately, I need this function a couple of times to compare a DNS with an IP-address.
For some reason I get a big Memory Leak and the memory of my program increases very fast.
Why is that and how can I free the memory?
Thanks in advance.
This code does not leak. Either your leak detection is faulty, or the code you are actually running is more complex than this and the leak is in the code that you have not shown.
The only memory allocated by the Delphi RTL, in the code in the question, is for the dynamic strings. Delphi dynamic string handling does not leak. The calls to WinSock,
gethostbynameandinet_ntoaallocate memory internal to WinSock.In the case of
gethostbyname:And likewise for
inet_ntoa:Whilst it is true that the code in the question does not call
WSACleanupthat’s fine since it is rather pointless to reclaim resources at process termination time.