“” Is Not The Same As NULL

I have been very busy recently. Aside from Starcraft II, I picked up another side programming project. I am reworking an old MFC app and see how far I can bring it into modern age with MFC9.0.

MFC is horrible in practice because it forces you to deal all the details, such as resizing and redrawing. But it suits my purpose because it forces me to learn all the details.

As I was testing the application across Window XP and Window 7, I noticed a strange error. The Create() function of CAsyncSocket returns an error 10022 on Window 7, and not Window XP.

// pueudocode

// Create a server socket, CMyAsyncSocket is derived from CAsyncSocket.
m_serverSocket = new CMyAsyncSocket();
BOOL hasError = m_serverSocket->Create(
   m_listenPort, // some port number to bind to
   SOCK_STREAM,
   FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
   "");
if(TRUE == hasError)
{
   int error = GetLastError();
   ... // report and print error
}
... // more code here

Error 10022 is WSAEINVAL, where it indicates that an invalid argument was supplied.

Instead of reading the error code, my cognitive bias convinced me that the above code is flawless since it worked in XP. I jumped through the hoops to change firewall settings, network card settings, and tried to blame everything but the source.

Eventually I went back and inspect the API again, and realized that the third and fourth arguments are already defaulted to the appropriate values.

// CAsyncSocket signature
BOOL Create(
   UINT nSocketPort = 0,
   int nSocketType = SOCK_STREAM,
   long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
   LPCTSTR lpszSocketAddress = NULL
);

So I cleaned up the function call to Create().

//...

m_serverSocket->Create(
   m_listenPort, // some port number to bind to
   SOCK_STREAM);

//...

Apparently the application was setting lpszSocketAddress to “” instead of NULL, it is an invalid argument (as indicated by the MFC for ~5000 times before it penetrated my thick head).

With the appropriate argument, everything works.

Leave a Reply

Your email address will not be published. Required fields are marked *