devxlogo

Release All Resources Before Exiting a Function

Release All Resources Before Exiting a Function

This code snippet releases memory and closes all open handles, files, etc. before exiting a function. Even if a function has to return, for whatever reason, this code ensures all resources remain released.

The code, which is written in a function, is written in the __try & __finally block.

Here is small example:

#define MYCONSTANT "OK THIS IS A TEST"bool function(){    int a = 0;    char* ptrMem = new char[51];    strcpy(ptrMem, MYCONSTANT);    __try    {       printf("Enter a number : - ");       scanf("%d",&a);       fflush(stdin);       if(0 == (a%2))       {           //some problem, required to quit           return false;       }       else       {           //No problem do the required operations           //and delete the memory         }    }   __finally   {         if(NULL != ptrMem)          {               delete [] ptrMem;               ptrMem = NULL;          }   } }

The __try and __finally blocks take care that at any time the function returns, it deallocates the allocated memory. This block is very important, for releasing all the allocated resources, hence making sure that all the resources are properly deallocated&?meaning, no more memory leaks, open handles, etc.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist