Discussing the nuts and bolts of software development

Friday, January 11, 2008

 

time_t fun!

"When using Visual Studio 2005 and later, the time_t datatype defaults to an 8-byte datatype, not the 4-byte datatype used for the LeaseObtained and LeaseExpires members on a 32-bit platform. To properly use the IP_ADAPTER_INFO structure on a 32-bit platform, define _USE_32BIT_TIME_T (use -D _USE_32BIT_TIME_T as an option, for example) when compiling the application to force the time_t datatype to a 4-byte datatype." — from MSDN Library

So when you are calling functions such as GetAdaptersInfo on a 32 bit machine you need to take such things into account.

i.e.
...
IP_ADAPTER_INFO* pAdptInfo = NULL;
ULONG ulLen = 0;
time_t t1;
time_t t2;
CWinErr err;

err = GetAdaptersInfo(NULL, &ulLen); // call with NULL to get size required

// At this point ulLen==640 but the IP_ADAPTER_INFO I compiled is 648 bytes because
// the two time_t members, IP_ADAPTER_INFO::LeaseObtained and IP_ADAPTER_INFO::LeaseExpires
// are 8-byte each.

if (err == ERROR_BUFFER_OVERFLOW)
{
// Adding the following assert helped us locate a problem
// ASSERT(ulLen >= sizeof(IP_ADAPTER_INFO));

pAdptInfo = (IP_ADAPTER_INFO*)malloc(ulLen);

err = GetAdaptersInfo(pAdptInfo, &ulLen); // Iphlpapi.dll on 32 bit machine uses 4-byte time_t
}

if (pAdptInfo && err == ERROR_SUCCESS)
{
t1 = pAdptInfo->LeaseObtained;
t2 = pAdptInfo->LeaseExpires; // Craps out with access violation here because this
// member is actually the last 8 bytes of the struct
// which I haven't allocated in with my malloc call.
}
...


Thanks for the warning MS! Now people will probably argue that the warning is in the IP_ADAPTER_INFO MSDN page or I that I should have read this page but I'm not converting my application to 64 bit, I was simply converting my VS2003 solution to VS2005!

Labels: , ,


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?