C6242

 

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

For the latest documentation on Visual Studio 2017, see C6242 on docs.microsoft.com. warning C6242: A jump out of this try-block forces local unwind. Incurs severe performance penalty

This warning indicates that a jump statement causes control-flow to leave the protected block of a try-finally other than by fall-through.

Leaving the protected block of a try-finally other than by falling through from the last statement requires local unwind to occur. Local unwind typically requires approximately 1000 machine instructions; therefore, it is detrimental to performance.

Use _leave to exit the protected block of a try-finally.

The following code generates this warning:

#include <malloc.h>  
void DoSomething(char *p); // function can throw exception  
  
int f( )  
{  
   char *ptr = 0;  
   __try   
   {  
      ptr = (char*) malloc(10);  
      if ( !ptr )   
      {  
         return 0;   //Warning: 6242  
      }  
      DoSomething( ptr );  
   }  
   __finally   
   {  
      free( ptr );  
   }  
   return 1;  
}  

To correct this warning, use __leave as shown in the following code:

#include <malloc.h>  
void DoSomething(char *p);   
int f()  
{  
   char *ptr = 0;  
   int retVal = 0;  
  
   __try   
   {  
      ptr = (char *) malloc(10);  
      if ( !ptr )  
      {  
         retVal = 0;  
         __leave;   //No warning  
      }  
      DoSomething( ptr );  
      retVal = 1;  
   }  
   __finally  
   {  
      free( ptr );  
   }  
  
   return retVal;  
}  

The use of malloc and free have many pitfalls in terms of memory leaks and exceptions. To avoid these kinds of leaks and exception problems altogether, use the mechanisms that are provided by the C++ Standard Template Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers and C++ Standard Library.

try-finally Statement

Show: