Question

According to MSDN documentation for OLE conversion macros, if we use a macro in a for loop for example, it may end up allocating more memory on stack leading to stack overflow.

This is the example provided on MSDN

void BadIterateCode(LPCTSTR* lpszArray)
{
   USES_CONVERSION;
   for (int ii = 0; ii < 10000; ii++)
      pI->SomeMethod(ii, T2COLE(lpszArray[ii]));
}

In the above example T2COLE is used inside a for loop which may lead to stack overflow, to avoid this the method call is encapsulated into a function like this

void CallSomeMethod(int ii, LPCTSTR lpsz)
{
   USES_CONVERSION;
   pI->SomeMethod(ii, T2COLE(lpsz));
}

void MuchBetterIterateCode2(LPCTSTR* lpszArray)
{
   for (int ii = 0; ii < 10000; ii++)
      CallSomeMethod(ii, lpszArray[ii]);
}

Can we just send the LPCTSTR to another function instead of encapsulating the whole method like this,

LPCOLESTR CallSomeMethod(LPCTSTR lpsz)
{
   USES_CONVERSION;
   return T2COLE(lpsz);

}

void BadIterateCode(LPCTSTR* lpszArray)
{
       for (int ii = 0; ii < 10000; ii++)
       pI->SomeMethod(ii, CallSomeMethod(lpszArray[ii]));
}

Can anyone tell me if it is safe use of OLE macro or still we may run into stack overflow?

Will there be any other issues by using the above method?

Was it helpful?

Solution

The third example will not work because the T2COLE object created in the method will be destroyed as soon as you return from the function. As you note in your question, the object is created on the stack, and the usual stack rules apply in this situation - the object will be destroyed as soon as you go out of scope, and you'll be accessing garbage data in the 3rd case.

The second case is the correct mechanism to use for using the data without triggering a stack overflow as upon return from the function, the memory that was allocated by the T2COLE will be freed.

I'm not aware of how the implementation of T2COLE works, but in C, you could achieve the same behaviour by using the alloca function which suffers from the same issue - as soon as you return from the function, you should consider the pointer and the data that it points at as invalid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top