CAsyncSocket leaks

Has anybody come across this problem before? MFC CAsyncSocket will leak memory if you repeatedly create, bind and close the socket in a loop within a single thread provided there are no other CAsyncSocket objects alive during the duration of the test.

For example, the following code will leak:

void leak(){while (true) { CAsyncSocket socket; socket.Create(); } }

while the following code will not leak:

void noleak() { CAsyncSocket dummy; dummy.Create();while (true) { CAsyncSocket socket; socket.Create(); } }

The difference is that the dummy socket object in the noleak() function is kept alive during the duration of the while loop. In the CAsyncSocket::Create method it calls CAsyncSocket::AttachHandle. This will create a new notification window if it is the first CAsyncSocket to require that window for the current thread. The window belongs to the current thread state. In the leak() function, a CAsyncSocket is repeately created and destroyed, leading to this notification window for the thread to be repeatedly created and destroyed. In noleak() the notification window is created just once when dummy gets created and then it is re-used by socket during the while loop. This is the only difference that I can see. So the memory leak can be avoided by keeping at least one CAsyncSocket object alive for the duration of the thread even if that socket is not used for communication (as long as you call Create on it to force the notification window to be created just once per thread.)

I can reproduce this bug in VC6.0 and 7.1. I have not tried 8.0

[2040 byte] By [BradHeide] at [2007-12-22]
# 1

Good find. You should open a bug on this here: http://connect.microsoft.com/feedback/default.aspx?SiteID=210

BrianKramer at 2007-8-30 > top of Msdn Tech,Visual C++,Visual C++ Language...
# 2

I went to the feedback site as you suggested and it happens that this problem has already been reported: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99822

It is apparently a problem with Win XP that they say is fixed in the next OS (Vista.) Because there is a workaround (keep at least one socket alive at all times) they do not intend to fix it in the current OS.

BradHeide at 2007-8-30 > top of Msdn Tech,Visual C++,Visual C++ Language...