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

