views:

72

answers:

1

Hi,

I'm using Visual Studio C++ 2010 Express. I made this function with variable argument list:

BOOL Send(SOCKADDR_IN toAddr, LPTSTR command, LPTSTR first, ...) {
 if (g_udpSocket == INVALID_SOCKET || command == NULL)
  return FALSE;

 va_list args; 
 va_start(args, command);
 LPTSTR str = va_arg(args, LPTSTR);
 TCHAR szData[DEFAULT_STR_LEN] = {0};
 _tcscpy(szData, command);      
 while (str != NULL) {
  _tcscat(szData, TEXT(" "));
  _tcscat(szData, str);
  str = va_arg(args, LPTSTR);
 }
 va_end(args);

 TCHAR szEncrypted[DEFAULT_STR_LEN] = {0};
 DWORD bytesEncrypted = EncryptString((LPBYTE)szData, _tcslen(szData) * sizeof(TCHAR), (LPBYTE)szEncrypted, DEFAULT_STR_LEN * sizeof(TCHAR));

 return sendto(g_udpSocket, (char*)szEncrypted, bytesEncrypted, 0, (SOCKADDR*) &toAddr, sizeof(toAddr)) > 0;
}

Example call:

Send(g_listener, CMD_APP, currentAppTitle, NULL);

I'm using NULL to indicate that the parameters list ended. Everything runs fine on debug configuration, but when I switch to release the optimizations mess up the variable argument. Any type of optimization doesn't work (/Od, /O1, /O2, ...).

Despite the fact I'm using TCHAR macros, the project is not using UNICODE nor MBCS.

Any ideas how to keep optimizations on (minimize size) and make the variable argument list work?

Thanks, Arth

+1  A: 

The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.

The parameter last is the name of the last parameter before the variable argument list, i.e., the last parameter of which the calling function knows the type.

Your code reads:

BOOL Send(SOCKADDR_IN toAddr, LPTSTR command, LPTSTR first, ...) {

  /* ... */

  va_start(args, command);

command should be first, or the first parameter should be removed.

strager
Actually, `first` just needs to go away.
Ben Voigt
@Ben Voigt, Or that; it depends on the caller code. (The example call isn't too clear.)
strager
In fact that was the problem, still weird it work fine on debug configuration and it didn't work on release configuration.Thank you Ben Voight
Arth