Memory leak in function

Greetings, I'm creating a simple ping library to use in a larger project, but it seems that I've got myself a memory leak and I'm finding it hard to localize it. I'd appreciate if anyone could give me a tip how to find it.
Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <WinSock2.h>
#include <IPHlpApi.h>
#include <IcmpAPI.h>
#include <stdio.h>

#define DllExport __declspec(dllexport)

extern "C"
{
	float DllExport libIcmpSendEcho(char *ip_addr, int size, int timeout)
	{
		HANDLE icmpHandle = IcmpCreateFile();
		char *sendBuffer = new char[size];
		IPAddr netaddr = inet_addr(ip_addr);
		unsigned long replySize = sizeof(ICMP_ECHO_REPLY) + size;
		LPVOID replyBuffer = (void*) malloc(replySize);


		DWORD response = IcmpSendEcho(icmpHandle,netaddr , sendBuffer, size, NULL, replyBuffer, replySize, timeout);
		printf("Response from Send Echo is: %d\n", response);
		if (response>0)
		{
			PICMP_ECHO_REPLY reply = (PICMP_ECHO_REPLY)replyBuffer;
			printf("RTT: %d\n", reply->RoundTripTime);
			IcmpCloseHandle(icmpHandle);
			delete replyBuffer, sendBuffer;
			return reply->RoundTripTime;
		}
		else
		{
			printf("Error %d\n", GetLastError());
			IcmpCloseHandle(icmpHandle);
			delete replyBuffer, sendBuffer;
			return GetLastError();
		}
	}
}

Whenever I compile a program with
1
2
3
4
5
6
7
int main()
{
     while(true)
     {
          libIcmpSendEcho("127.0.0.1",32,100);
     }
}

my program's memory size is constantly increasing. Thanks in advance.
please find the difference between:

1) delete ptr;
2) delete [] ptr;

where ptr is your sendBuffer

Also consider not using delete to memory that were allocated by malloc
Last edited on
Lines 26 and 33 are wrong. The delete operator doesn't distribute itself to all members separated by comma. See http://msdn.microsoft.com/en-us/library/zs06xbxh(VS.80).aspx or http://en.wikipedia.org/wiki/Comma_operator .

EDIT: Oh, look at that. Ivan caught some good ones too. If you allocate with malloc(), you must deallocate with free().
Last edited on
delete replyBuffer, sendBuffer;
Error is right there. Look up the comma operator - this only deletes replyBuffer, not sendBuffer.
And the use of delete is wrong for both - memory allocated by malloc must be freed via free() and memory allocated by new[] must be freed via delete[].

Edit: too slow.
Last edited on
Thank you, works perfectly.
Topic archived. No new replies allowed.